我正在尝试向我的 df 添加一列,如果 B <A 返回“是”,如果 B>= A 则返回“否”。但是,如果 A 或 B 包含缺失值,则应返回 np.nan。
因此,我想要的输出看起来像这样:
| 一种 | 乙 | is_less |
|---|---|---|
| np.nan | 10 | np.nan |
| 10 | np.nan | np.nan |
| 1 | 5 | 不 |
| 5 | 1 | 是的 |
问题:我的代码在需要时不返回 np.nan。
我尝试过的:选项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'])
不幸的是,A 或 B 列中的 np.nans 被忽略,导致 'is_lessl.
选项 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)
应用此函数会产生“yes”、“no”和 0 的混合结果,但不会返回 np.nans。
我该如何解决这个问题?