繁体   English   中英

Python:用于数据帧切片的pandas数据帧条件

[英]Python: pandas dataframe condition for slice of a dataframe

我想更改pandas dataframe列中的内容,如果条件满足,则只在列中包含'ABC'。 我尝试下面的代码,但它返回此错误

 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 
 print df

   Item  Price  Quantity
0  ABC    10     30
1  ABB    20     50 
2  ABC    37     89
3  ABG    5      78

con1 = df['Price']>10
con2 = df['Quantity']>20
df[df['Item']=='ABC'].loc[con1 & con2,'Item'] = 'ABCD'

Output that I want

   Item  Price  Quantity
0  ABC    10     30
1  ABB    20     50 
2  ABCD   37     89
3  ABG    5      78

警告是由链式索引引起的(首先制作切片然后在该切片上使用.loc )。 df['Item']=='ABC'只是你可以在.loc使用的另一个条件:

df.loc[con1 & con2 & (df['Item']=='ABC'), 'Item'] = 'ABCD'

con1 = df['Price']>10 con2 = df['Quantity']>20 con3 = df['Item'] == 'ABC' df['Item'][(con1) & (con2) & (con3)] = 'ABCD'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM