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

How to add new column in python containing non-zero values from other columns

I would like to add a new column to my dataframe containing the min values from columns b,d,g,(in-between there are other unimportant columns). If these columns (b,d,g) contain only 0s or NaN, then the new column should containt a 0, otherwise take the lowest non-zero value from b,d,g and fill in in the new column: something like this:

b d g new_column
0 0 0 0
2 5 0 2
1 0 1 1

>Solution :

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

You can try

cols = ['b', 'd', 'g']

df['res'] = df[cols][df[cols].ne(0)].min(axis=1).fillna(0)
print(df)

     b    d    g  new_column  res
0  0.0  0.0  0.0           0  0.0
1  2.0  5.0  0.0           2  2.0
2  1.0  0.0  1.0           1  1.0
3  NaN  NaN  0.0           0  0.0
4  NaN  NaN  NaN           0  0.0
5  NaN  1.0  NaN           1  1.0
6  0.0  1.0  NaN           1  1.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