Reputation: 471
let's say you have the following df:
In [1]: df15 = pd.DataFrame([[1, 2, True], [1, 3, False], [4, 6, True]], columns=['BTW', 'ExclBTW','is_na'])
Now I want to calculate a new column, taxrate#1, when the value of 'is_na' is True.
I've tried the following code:
for i, row in df15.iterrows():
if df15.loc[i,'is_na'] == True:
df15['taxrate#1'] = df15['BTW'].astype(float) / df15['ExclBTW'].astype(float)
else:
pass
However, this gets the operation on all values. Somehow I can't get the if statement to work..
Desired output:
BTW ExclBTW is_na taxrate#1
0 1 2 True 0.010526
1 1 3 False NaN
2 4 6 True 0.66
Please help!
Upvotes: 0
Views: 54
Reputation: 1875
You can use numpy:
import numpy as np
df15['taxrate#1'] = np.where(df15['is_na'] == True,
round(df15['BTW'] / df15['ExclBTW'], 2),
np.nan)
In your condition first value in output should give 0.5 if we divide BTW by ExclBTW.
Upvotes: 1