create new column based on multiple conditions in the same data frame

You can either concatenate conditions within the np.where() in the false argument, or create a custom function with your criteria and pass it using apply with lambda I will showcase both option:

Using multipe np.where():

df['new column'] = np.where(df['S1'].isna(),'New',
   np.where(df['S2']>df['S1'],'More',
      np.where(df['S2'] < ['S1'],'Less','Same')))

Creating a custom function:

def my_function(x):
   if x['S1'].isna():
      return 'New'
   elif x['S2'] > x['S1']:
      return "More"
   elif x['S2'] < x['S1']:
      return "Less"
   else:
      return "Same"

df['New column'] = df.apply(lambda x: my_function(x),axis=1)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top