pandas :如果满足3列中的条件,则更新值

编程入门 行业动态 更新时间:2024-10-22 10:38:36
本文介绍了 pandas :如果满足3列中的条件,则更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个像这样的数据框:

I have a dataframe like this:

In[1]: df Out[1]: A B C D 1 blue red square NaN 2 orange yellow circle NaN 3 black grey circle NaN

,并且我想在D列满足3个条件时进行更新.例如:

and I want to update column D when it meets 3 conditions. Ex:

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

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

It works for the first two conditions, but it doesn't work for the third, thus:

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

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

A better way of achieving this seems to be:

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

更多推荐

pandas :如果满足3列中的条件,则更新值

本文发布于:2023-10-24 14:00:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524119.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:则更   条件   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!