Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Decrement a dataframe column based on a condition

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading