【问题标题】:Replace column values based on a filter [duplicate]根据过滤器替换列值[重复]
【发布时间】:2022-01-12 10:09:17
【问题描述】:

鉴于此列表

a = [a,d]

给出这样的数据集

id type
a cat
b fish
c dog
d cat

如果数据集的id项在列表a中找到,那么我需要更改相关的type项,如果没有留下同类型的物品

最终结果

id type
a bird
b fish
c dog
d bird

此代码无效

df["type"] = np.where(df["id"].isin(a), df["type"].replace("bird"), df["type"])

【问题讨论】:

    标签: python-3.x pandas numpy


    【解决方案1】:

    如果匹配条件,只设置bird,如果需要设置相同的值,这里不需要replace

    df["type"] = np.where(df["id"].isin(a), "bird", df["type"])
    

    【讨论】:

      猜你喜欢
      • 2020-04-05
      • 2021-05-09
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多