python某列符合条件则全部_python – pandas:如果满足3列条件,则更新值

我有这样的数据帧:

In[1]: df

Out[1]:

A B C D

1 blue red square NaN

2 orange yellow circle NaN

3 black grey circle NaN

我想在满足3个条件时更新D列.例如:

df.ix[ np.logical_and(df.A=='blue', df.B=='red', df.C=='square'), ['D'] ] = 'succeed'

它适用于前两个条件,但它不适用于第三个条件,因此:

df.ix[ np.logical_and(df.A=='blue', df.B=='red', df.C=='triangle'), ['D'] ] = 'succeed'

有完全相同的结果:

In[1]: df

Out[1]:

A B C D

1 blue red square succeed

2 orange yellow circle NaN

3 black grey circle NaN

解决方法:

使用:

df[ (df.A=='blue') & (df.B=='red') & (df.C=='square') ]['D'] = 'succeed'

发出警告:

/usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py:2: SettingWithCopyWarning:

A value is trying to be set on a copy of a slice from a DataFrame.

Try using .loc[row_indexer,col_indexer] = value instead

实现这一目标的更好方法似乎是:

df.loc[(df['A'] == 'blue') & (df['B'] == 'red') & (df['B'] == 'square'),'label'] = 'M5'

标签:python,pandas

来源: https://codeday.me/bug/20191004/1852407.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值