[英]Pandas dataframe replace values on multiple column conditions
I have a dataframe df_merchandise with two columns of interest, ProductType and ProductDescription.我有一个数据框 df_merchandise,其中包含两列感兴趣的 ProductType 和 ProductDescription。 One of the values for ProductType is 'Accessory' which can have multiple different values for ProductDescription, such as 'Lamp', 'Mirror', etc. How would I do a conditional replacement like the following: ProductType 的值之一是“Accessory”,它可以有多个不同的 ProductDescription 值,例如“Lamp”、“Mirror”等。我将如何执行如下条件替换:
If (df_merchandise.ProductType == 'Accessory') and (df_merchandise.ProductDescription == 'Mirror'):
replace 'Accessory' with 'Mirror'
The key here being that I only replace the value of ProductType for ProductDescription if the row value for PType is 'accessory' AND the row value for PDesc.这里的关键是,我只能更换ProductType的价值产品描述如果PTYPE行值是“附件”和PDesc行值。 is 'Mirror'.是“镜子”。
If your original DF is如果您的原始 DF 是
ProductDescription ProductType
0 Art Accessory
1 Mirror Accessory
2 Western Art Accessory
3 Tassel Accessory
4 Hardware Accessory
5 Mirror Accessory
You can do the following:您可以执行以下操作:
mirror_filter = (df['ProductType'] == 'Accessory') & (df['ProductDescription'] == 'Mirror')
df.loc[mirror_filter, 'ProductType'] = df['ProductDescription']
And your resulting DF should be:你得到的 DF 应该是:
ProductDescription ProductType
0 Art Accessory
1 Mirror Mirror
2 Western Art Accessory
3 Tassel Accessory
4 Hardware Accessory
5 Mirror Mirror
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.