Reputation: 3
For example, I have the following data frame df
r1 r2
1 False 10
2 True 20
3 True 40
I would like to change the value of r2 to become the value of its index to the power of its index if r1 is True
pow(index, index)
The desired result is
r1 r2
1 False 10
2 True 4
3 True 27
I know how to target the cells which the values need to be changed, but I just know how to set them to a constant i.e. 0
df.loc[df['r1'] == True, 'r2'] = 0
But I don't know how to set it to a function of its index
Thank you for the help
Upvotes: 0
Views: 61
Reputation: 294516
Using pd.DataFrame.mask
df.r2.mask(df.r1, df.index ** df.index, inplace=True)
df
r1 r2
1 False 10
2 True 4
3 True 27
Upvotes: 2
Reputation: 403130
Use df.r1
to find the index, then index r2
and reassign.
idx = df[df['r1']].index
df.loc[df['r1'], 'r2'] = idx ** idx
print(df)
r1 r2
1 False 10
2 True 4
3 True 27
Upvotes: 1