Home > database >  How to get another column in a dataframe filled with values from another columns based on multiple c
How to get another column in a dataframe filled with values from another columns based on multiple c

Time:11-05

I have a dataframe with 6 columns:

Id  count1  Value1  count2  Value2  Value3  
1    1200      3     2000       4       6     
2    100       2     400        5       8     
3    800       4     1100       7       9  

I need to get a new column with following conditions: if count 1 > 1000, new column should take values from Value1 column. elif count 2 > 1000, new column should take values from Value2 column. else, new column should be filled with values from Value 3.

Output should look like:

Id  count1  Value1  count2  Value2  Value3  New Column
1    1200      3     2000       4       6     3
2    100       2     400        5       8     8
3    800       4     1100       7       9     7

CodePudding user response:

you can use np.select()

import numpy  as np

condlist=[(df['count1'] > 1000),(df['count2'] > 1000) & (df['count1'] <= 1000)]
choicelist=[df['Value1'], df['Value2']]
default=df['Value3']

df['new_column']=np.select(condlist,choicelist,default)
  • Related