Home > Enterprise >  How to change an operation to other column when value is equal to nan in a dataframe?
How to change an operation to other column when value is equal to nan in a dataframe?

Time:08-02

I have a data frame with three columns "dayO", "dayN" and "dayF", I want to create another column named "days" where it substracts the value of dayN with dayO only if dayN is not equal to nan, otherwise it should substract the value from dayF.

I have tried using apply and lambda like this:

df['days']=df.apply(lambda x: x['dayN']-x['dayO'] if x['dayN'].notnull() else x['dayF']-x['dayO'])

but it results in this error: raise KeyError(key) from err KeyError: 'dayN'

CodePudding user response:

Use fillna to replace the NaN of dayN with dayF during the operation:

df['days'] = df['dayN'].fillna(df['dayF'])-df['dayO']

CodePudding user response:

dataOpen['days']=np.where(dataOpen.dayN.notnull(),dataOpen['dayN']-dataOpen['dayO'],dataOpen['dayF']-dataOpen['dayO'])

this seems to work

  • Related