Skip to main content
 首页 » 编程设计

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

2025年05月04日17zhoujg

我有一个这样的数据框,

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

我尝试创建三个新列,a、b 和 c,如果它包含特定字符串,则给出“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)