Home > Back-end >  How to add new column in python containing non-zero values from other columns
How to add new column in python containing non-zero values from other columns

Time:07-25

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

CodePudding user response:

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
  • Related