如何在 Python Pandas 中比较 2 个 DataFrame 中列之间的值?

How to compare values between columns in 2 DataFrames in Python Pandas?

提问人:dingaro 提问时间:4/18/2023 更新时间:4/19/2023 访问量:47

问:

我在 Python Pandas 中有 2 个数据帧,如下所示:

输入:

df1 = pd.DataFrame({"col1":["APPLE", "BANANA", "ORANGE"]})
df2 = pd.DataFrame({"col_x":["APPLEXX", "BANANA", "CARROT"]})

DF1:

col1
------
APPLE
ORANGE
BANANA

DF2:

col_x
--------
APPLEXX
BANANA
CARROT

要求:

我只需要打印 df2 (col_x) 中的行,其中: 包含来自 df1 (col1) 的值,作为 df2 (col_x) 中值的一部分或全部,以及它们在 df1 (col1) 中的等效值

欲望输出:

因此,作为输出,我需要如下所示的内容:

COL1型 col_x
苹果 APPLEXX公司
香蕉 香蕉

如何在 Python Pandas 中做到这一点?

熊猫 数据帧 合并 伊辛

评论

1赞 RomanPerekhrest 4/18/2023
这些数据帧有多大?

答:

0赞 RomanPerekhrest 4/18/2023 #1

您可以利用赋值表达式(从 python 3.8 开始)和生成器表达式的内置 next 方法:

df = pd.DataFrame([[s, w] for w in df2['col_x']
                   if (s := next((x for x in df1['col1'] if x in w), None))])
print(df)

        0        1
0   APPLE  APPLEXX
1  BANANA   BANANA

对于较旧的 python 版本,请使用以下生成器函数:

def match_gen(s1, s2):
    for word in s1:
        match = next((x for x in s2 if x in word), None)
        if match:
            yield (match, word)

df = pd.DataFrame(match_gen(df2['col_x'], df1['col1']))