Home > Software engineering >  Pandas dataframe divide column depending on value of other column
Pandas dataframe divide column depending on value of other column

Time:02-23

I have a DataFrame that looks like this:

Currency   AmountInUSD
FR         100
US         200
JP         1000

What I'd like to do is, whenever we have rows where "Currency" is equal to "JP", divide its AmountInUSD by 100. So the result should look like this:

Currency   AmountInUSD
FR         100
US         200
JP         10

How do I achieve this?

CodePudding user response:

If Currency is your index, you can use iloc to find the rows that you want to apply a transformation to :

import pandas as pd
df = pd.DataFrame({'AmountInUSD':[100,200,1000]}, index = ['FR','US', 'JP'])

df['AmountInUSD'].iloc[df.index == 'JP']/=100

else just select the rows where df.Currency == 'JP'

df = pd.DataFrame({'AmountInUSD':[100,200,1000], 'Currency': ['FR','US', 'JP']}, index = [1,2,3])
df['AmountInUSD'][df.Currency == 'JP']/=100
print(df)

CodePudding user response:

You could mask the Amounts corresponding to "JP" currency and replace:

df['AmountInUSD'] = df['AmountInUSD'].mask(df['Currency'].eq('JP'), df['AmountInUSD']/100)

Output:

  Currency  AmountInUSD
0       FR          100
1       US          200
2       JP           10
  • Related