熊猫数据框替换多个列条件下的值

时间:2020-10-28 17:15:00

标签: python pandas dataframe filter replace

我有一个数据框df_merchandise,其中有两个感兴趣的列,即ProductType和ProductDescription。 ProductType的值之一是“ Accessory”,它对于ProductDescription可以具有多个不同的值,例如“ Lamp”,“ Mirror”等。我将如何像下面这样进行条件替换:

If (df_merchandise.ProductType == 'Accessory') and (df_merchandise.ProductDescription == 'Mirror'):
     replace 'Accessory' with 'Mirror'

这里的关键是,仅当PType的行值为'accessory' AND PDesc的行值时,才替换ProductDescription的ProductType值。是“镜子”。 pandas dataframe

1 个答案:

答案 0 :(得分:2)

如果原始DF是

  ProductDescription ProductType
0                Art   Accessory
1             Mirror   Accessory
2        Western Art   Accessory
3             Tassel   Accessory
4           Hardware   Accessory
5             Mirror   Accessory

您可以执行以下操作:

mirror_filter = (df['ProductType'] == 'Accessory') & (df['ProductDescription'] == 'Mirror')
df.loc[mirror_filter, 'ProductType'] = df['ProductDescription']

您生成的DF应该是:

  ProductDescription ProductType
0                Art   Accessory
1             Mirror      Mirror
2        Western Art   Accessory
3             Tassel   Accessory
4           Hardware   Accessory
5             Mirror      Mirror