gpt4 book ai didi

python - 更改与 python 中第二个数据帧匹配的行的第一个数据帧的值

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:56 25 4
gpt4 key购买 nike

例如,如果第一个数据帧 df1是:

     'a' 'b' 'value'
0 1 2 1
1 2 3 1

和第二个数据框df2

     'a' 'b' 
0 1 2

我想要得到类似的东西

     'a' 'b' 'value'
0 1 2 0
1 2 3 1

对于 df1 中与 df2 中的行匹配的所有行(不包括“值”列),我想将 df1 中这些行的“值”列从 1 更改为 0。我可以通过以下方式找到公共(public)行使用df1.merge(df2, on=['a','b']) 。但如何更改该值呢?

最佳答案

合并时可以指定indicator参数为true,这样会生成一个额外的列,指定行是否来自两边,然后可以修改基于 _merge 列的值列:

df_merge = df1.merge(df2, indicator=True, how = "left")
df_merge["value"] = df_merge["value"].where(df_merge['_merge'] != "both", 0)
df_merge.drop("_merge", axis=1)

# a b value
#0 1 2 0
#1 2 3 1
<小时/>

另一种选择:

df1 = df1.set_index(['a', 'b'])
df1.loc[df2.set_index(['a', 'b']).index, 'value'] = 0
df1.reset_index()

# a b value
#0 1 2 0
#1 2 3 1

关于python - 更改与 python 中第二个数据帧匹配的行的第一个数据帧的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41755418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com