简体   繁体   中英

Pandas dataframe divide column depending on value of other column

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?

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'].loc[df.Currency == 'JP']/=100
print(df)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM