gpt4 book ai didi

python - 在Python中比较两个数据帧值

转载 作者:太空宇宙 更新时间:2023-11-03 16:12:48 24 4
gpt4 key购买 nike

我有两个数据帧 df1['LicId']df2['LicId']

df1['LicId'] 始终只有一个值

    LicId
0 abc1234

但是 df2['LicId'] 将有多个 Id

    LicId
0 abc1234
1 xyz2345

我的任务是将 df1['LicId']df2['LicId'] 进行比较,并仅在两者匹配时才执行代码。

我已经尝试过:

if df1['LicId'][0]==df2['LicId'][0]:
remaining code

但是,这只会检查 abc1234 - 它必须检查 df2 的所有索引值。稍后,我可能还会在 df1 中拥有 xyz2345

有人可以告诉我如何处理这个问题吗?

最佳答案

您可以使用 isin() 来匹配值:

df1 = pd.DataFrame({'LicId':['abc1234', 'a', 'b']})
df2 = pd.DataFrame({'LicId':['abc1234', 'xyz2345', 'a', 'c']})

df1:

     LicId
0 abc1234
1 a
2 b

df2:

     LicId
0 abc1234
1 xyz2345
2 a
3 c

匹配值:

if len(df2.loc[df2['LicId'].isin(df1['LicId'])]) > 0:
print(df2.loc[df2['LicId'].isin(df1['LicId'])])
#remaining code

输出:

     LicId
0 abc1234
2 a

关于python - 在Python中比较两个数据帧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39127450/

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