I'm trying to add a column to my df that returns 'yes' if B <A and 'no' if B>= A. However, if either A or B contains a missing value, np.nan should be returned.
My desired output would therefore look something like this:
| A | B | is_less |
|---|---|---|
| np.nan | 10 | np.nan |
| 10 | np.nan | np.nan |
| 1 | 5 | no |
| 5 | 1 | yes |
Problem: my code doesn't return np.nan when required.
What I have tried: option 1:
df['is_less'] = np.where (df['B'] < df['A'], "yes", "no")
df['is_less'] = np.where (df['A'] == np.nan, np.nan, df['is_less'])
df['is_less'] = np.where (df['B'] == np.nan, np.nan, df['is_less'])
Unfortunately np.nans in column A or B are ignored, resulting in incorrect values in 'is_lessl.
Option 2:
def reduced_growth(x):
if (x['A'] == np.nan or x['B']==np.nan):
return np.nan
elif (x['B'] < x['A']):
return "yes"
elif (x['B'] >= x['A']):
return "no"
else:
return "0"
#create new feature using function
df['is_less']= df.apply(reduced_growth, axis=1)
Applying this function results in a mixture of 'yes', 'no' and 0, but no np.nans are returned.
How could I solve this problem?