如何在 Pandas DataFrame 中找到公共元素?
要查找PandasDataFrame中的公共元素,我们可以使用merge()带有列列表的方法
步骤
创建二维、大小可变、潜在异构的表格数据df1。
打印输入数据帧df1。
创建另一个二维表格数据df2。
打印输入数据帧df2。
使用merge()方法查找公共元素。
打印公共数据帧。
示例
import pandas as pd
df1 = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
df2 = pd.DataFrame(
{
"x": [5, 2, 7, 0, 11, 12],
"y": [4, 7, 5, 1, 19, 20],
"z": [9, 3, 5, 1, 29, 30]
}
)
print("Input DataFrame 1 is:\n", df1)
print("Input DataFrame 2 is:\n", df2)
common = df1.merge(df2, on=['x', 'y', 'z'])
print("Common of DataFrame 1 and 2 is: \n", common)输出结果Input DataFrame 1 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Input DataFrame 2 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 4 11 19 29 5 12 20 30 Common of DataFrame 1 and 2 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1