Home > Software engineering >  Python Pandas and list comprehension showing numbers in a weird format
Python Pandas and list comprehension showing numbers in a weird format

Time:12-05

I have a pandas dataframe like this:

Transaction Transaction Amount
Deposit 10.00
Dividend 0.9
Taxes 0.04

And I am applying a list comprehension like this:

df['Tax'] = ['0' if i == "Deposit" or i == "Dividend" else df['Transaction Amount'] for i in df['Transaction']]


df['Net Amount'] = [df['Transaction Amount'] if i == "Deposit" or i == "Dividend" else -1 * df['Tax'] for i in df['Transaction']]

However, for both I get a weird output like this: "0 1.00 1 1000.00 2 1000.00 3..."

Transaction Amount is a float64, I have tried to make it string, to see if that solves the issue, but I keep getting the same.

I'd appreciate the help, I am no python expert

CodePudding user response:

Try this using np.where instead of list comprehension.

import numpy as np
df['Tax'] = np.where(df['Transaction'].isin(['Deposit', 'Dividend']),
                     0 ,df['Transaction Amount'])

df['Net Amount'] = np.where(df['Transaction'].isin(['Deposit', 'Dividend']), 
                            df['Transaction Amount'], -1*df['Tax'])

Output:

  Transaction  Transaction Amount   Tax  Net Amount
0     Deposit               10.00  0.00       10.00
1    Dividend                0.90  0.00        0.90
2       Taxes                0.04  0.04       -0.04
  • Related