gpt4 book ai didi

python - 两列匹配列表的两个元素

转载 作者:行者123 更新时间:2023-12-01 22:40:59 25 4
gpt4 key购买 nike

我有一个包含两列的数据框:

import pandas as pd
data={'A':['x','y','z','r','x','z'],'B':[1,2,3,4,1,7]}
df=pd.DataFrame(data)

这让我很感动:

A | B
x | 1
y | 2
z | 3
r | 4
x | 1
z | 7

然后是一个包含两个元素的 n 个列表的列表:

list_of_lists=[['x',1],['x',4],['z',3],['y',1]]

我想查明每个 sub_list 的 1st 元素是否与列 A 匹配,第二个元素是否与列 B 匹配,得到像这样:

A | B | Match
x | 1 | True
y | 2 | False
z | 3 | True
r | 4 | False
x | 1 | True
z | 7 | False

考虑为列表中的每个元素创建两个列表,并在这两个条件下执行类似 np.where 的操作,但必须有一种更简洁的方法。

最佳答案

使用DataFrame.merge使用 helper DataFrame 和 left join 和 Indicator=True 参数,然后比较值 both:

df1 = df.merge(pd.DataFrame(list_of_lists, columns=df.columns), how='left', indicator=True)

df['Match'] = df1['_merge'].eq('both')
print (df)
A B Match
0 x 1 True
1 y 2 False
2 z 3 True
3 r 4 False
4 x 1 True
5 z 7 False

关于python - 两列匹配列表的两个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59390383/

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