交集、左差集、右差集

120 阅读1分钟

要获得两个 DataFrame AB 的交集、只在 A 中的数据,以及只在 B 中的数据,可以使用 pandas 库中的 merge 方法和 concat 方法。下面是示例代码:

import pandas as pd

# 创建DataFrame A
data_A = {
    'key': [1, 2, 3, 4, 5],
    'value_A': ['A1', 'A2', 'A3', 'A4', 'A5']
}
df_A = pd.DataFrame(data_A)

# 创建DataFrame B
data_B = {
    'key': [4, 5, 6, 7, 8],
    'value_B': ['B4', 'B5', 'B6', 'B7', 'B8']
}
df_B = pd.DataFrame(data_B)

print("DataFrame A:")
print(df_A)

print("\nDataFrame B:")
print(df_B)

# 交集
intersection = pd.merge(df_A, df_B, on='key')
print("\nIntersection of A and B:")
print(intersection)

# 只在 A 有的数据
only_in_A = df_A[~df_A['key'].isin(df_B['key'])]
print("\nOnly in A:")
print(only_in_A)

# 只在 B 有的数据
only_in_B = df_B[~df_B['key'].isin(df_A['key'])]
print("\nOnly in B:")
print(only_in_B)

输出结果:

DataFrame A:
   key value_A
0    1      A1
1    2      A2
2    3      A3
3    4      A4
4    5      A5

DataFrame B:
   key value_B
0    4      B4
1    5      B5
2    6      B6
3    7      B7
4    8      B8

Intersection of A and B:
   key value_A value_B
0    4      A4      B4
1    5      A5      B5

Only in A:
   key value_A
0    1      A1
1    2      A2
2    3      A3

Only in B:
   key value_B
0    6      B6
1    7      B7
2    8      B8

这段代码演示了如何获取两个 DataFrame 的交集、只在 A 中的数据以及只在 B 中的数据。通过使用 merge 方法,我们可以轻松地获取交集,而通过使用 isin 方法,我们可以找出只在一个 DataFrame 中存在的数据。