If I have a dataframe like this how can I decrement 'a' based on 'b'?
df = pd.DataFrame([[100,1], [100,2], [100,3], [100,4], [100,5]], columns=["a", "b"])
df.loc[df.b > 2, 'b'] = 1
df.loc[df.b % 2 == 0, 'a'] -= 10
df.loc[df.b % 2 != 0, 'a'] = np.NaN
Desired result:
a b
0 NaN 1
1 90 2
2 80 4
3 NaN 5
4 70 6
CodePudding user response:
You can subtract values in array created by np.arange
starting by 1
multiplied by 10
:
df.loc[df.b > 2, 'b'] = 1
m = df.b % 2 == 0
df.loc[m, 'a'] -= np.arange(1, m.sum() 1) * 10
#alternative
#df.loc[m, 'a'] -= np.arange(10, m.sum() * 10 10, 10)
df.loc[~m, 'a'] = np.NaN
print (df)
a b
0 NaN 1
1 90.0 2
2 80.0 4
3 NaN 5
4 70.0 6