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

Change cell value according to values within another column [pandas]

I have a dataframe such as

Names Value COLA COLB COLC
A     100   0    4    1
B     NaN   0    2    1
C     20    3    0    0
D     1     0    1    0
E     300   3    0    0

And I would like to change all the COLA,B and C values (except the 0) :

  • to 1 if the Value col > 30
  • to 2 if the Value col <=30 or NaN.

I should then get

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

Names Value COLA COLB COLC
A     100   0    1    1
B     NaN   0    2    2
C     20    2    0    0
D     1     0    2    0
E     300   1    0    0

Does someone have a sugestion ?

>Solution :

Use numpy.where with chain condition used for broadcasting – assign mask from Series to multiple columns, for set 0 multiple ouput to boolean mask for set 0:

cols = ['COLA','COLB','COLC']

df[cols] = np.where(df['Value'].gt(30).to_numpy()[:, None], 1, 2) * df[cols].ne(0)
print (df)
  Names  Value  COLA  COLB  COLC
0     A  100.0     0     1     1
1     B    NaN     0     2     2
2     C   20.0     2     0     0
3     D    1.0     0     2     0
4     E  300.0     1     0     0
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