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

I have a dataframe like this,

col1 col2 col3

1 apple a,b

2 car c

3 dog a,c

4 dog NaN

I tried to create three new columns, a,b and c, which give '1' if it contains a specific string, otherwise, '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)

But it seems NaN values were not handled correctly. It gives me a result like,

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

It should be all '0's in the 4th row. How can I change my code to get the right answer?

解决方案

What I will do

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值