我有以下df
,
days
NaN
70
29
我喜欢做
df['short_days'] = np.where(df.days < 30, 'Yes', 'No')
但是当它是NaN
,df.short_days = 'Not Applicable'
时,结果将是这样,
days short_days
NaN Not Applicable
70 No
29 Yes
答案 0 :(得分:2)
只要fillna
用您想要的任何东西填充nan值
import numpy as np
df['short_days'] = np.where(df.days < 30, 'Yes', 'No')
df['short_days'].fillna('Not Applicable',inplace=True)
days short_days
NaN Not Applicable
70 No
29 Yes
答案 1 :(得分:2)
在这里可以使用np.select
来定义default
值,使用起来更优雅:
df['short_days'] = np.select([df.days<30, df.days>=30],
['Yes', 'No'],
default='Not Applicable')
输出
days short_days
0 NaN Not Applicable
1 70.0 No
2 29.0 Yes