Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Pandas and list comprehension showing numbers in a weird format

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…"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading