根据条件将数据框替换为另一行

时间:2020-04-15 09:25:30

标签: python pandas dataframe

我有一个如下数据框:

    ean           product_resource_id        shop
----------------------------------------------------
    123           abc                        xxl
    245           bed                        xxl
    456           dce                        xxl
    123           0                          conr
    245           0                          horec

我想用{“ 0 "product_resource_id"”相同的ID替换ean

我想要得到这样的结果:

    ean           product_resource_id        shop
----------------------------------------------------
    123           abc                        xxl
    245           bed                        xxl
    456           dce                        xxl
    123           abc                        conr
    245           bed                        horec

任何帮助都会非常有帮助。预先感谢!

1 个答案:

答案 0 :(得分:1)

想法是对0中具有product_resource_id值的行进行过滤,如果不存在匹配值被替换,则按ean列删除重复项(如果存在),并按DataFrame.set_index创建Series进行映射。按原始值按Series.fillna值,因为不匹配的值返回NaN s:

#mask = df['product_resource_id'].ne('0')
#if 0 is integer
mask = df['product_resource_id'].ne(0)
s = df[mask].drop_duplicates('ean').set_index('ean')['product_resource_id']
df['product_resource_id'] = df['ean'].map(s).fillna(df['product_resource_id'])
print (df)
   ean product_resource_id   shop
0  123                 abc    xxl
1  245                 bed    xxl
2  456                 dce    xxl
3  123                 abc   conr
4  245                 bed  horec
相关问题