在 python 中使用 np.where 函数时如何避免 NaN?

How to avoid NaN when using np.where function in python?

我有一个这样的数据框,

col1    col2   col3
1       apple   a,b 
2       car      c
3       dog     a,c
4       dog     NaN

我尝试创建三个新列,abc,如果它包含特定字符串,则给出“1”,否则为“0”。

df['a']= np.where(df['col3'].str.contains('a'),1,0)
df['b']= np.where(df['col3'].str.contains('b'),1,0)
df['c']= np.where(df['col3'].str.contains('c'),1,0)

但似乎没有正确处理 NaN 值。它给了我这样的结果,

col1  col2  col3    a   b   c
1    apple   a,b    1   1   0
2     car     c     0   0   1
3     dog    a,c    1   0   1
4     dog    NaN    1   1   1

第4行应该全为'0'。我怎样才能更改我的代码以获得正确的答案?

我会做什么

s=df.col2.str.get_dummies(sep=',')
Out[29]: 
   a  b  c
0  1  1  0
1  0  0  1
2  1  0  1
3  0  0  0
df=pd.concat([df,s],axis=1)

您可以使用 fillna(False)。 您正在使用布尔索引,因此与 NaN 对应的值始终为 0

df['a']= np.where(df['col2'].str.contains('a').fillna(False),1,0)
df['b']= np.where(df['col2'].str.contains('b').fillna(False),1,0)
df['c']= np.where(df['col2'].str.contains('c').fillna(False),1,0)

输出:

   col1   col2 col3  a  b  c
0     1  apple  a,b  1  0  0
1     2    car    c  1  0  1
2     3    dog  a,c  0  0  0
3     4    dog  NaN  0  0  0