查找两个数据框共享的列
Pandas 是用于数据分析和操作的开源Python库。它快速、强大、灵活且易于使用。在本文中,我们将讨论如何查找两个数据帧之间的公共列。以下是可用于查找常见列的不同方法。
方法一:使用Numpy intersect1d方法
在此示例中,我们将从列表中创建 Pandas Dataframe,然后我们将使用 Numpy 的 intersect1d() 方法,该方法将返回两个 Dataframe 之间共有的列。
Python3
# Importing libraries
import pandas as pd
import numpy as np
# Creating Dataframes
a = [{'Name': 'abc', 'Age': 8, 'Grade': 3},{'Name': 'xyz', 'Age': 9, 'Grade': 3}]
df1 = pd.DataFrame(a)
b = [{'ID': 1,'Name': 'abc', 'Age': 8},{'ID': 2,'Name': 'xyz', 'Age': 9}]
df2 = pd.DataFrame(b)
# Printing Dataframes
display(df1)
display(df2)
# Finding Common columns
a = np.intersect1d(df2.columns, df1.columns)
# Printing common columns
print ("Common Columns:",a)
Python3
# Importing libraries
import pandas as pd
# Creating Dataframes
a = [{'Name': 'abc', 'Age': 8, 'Grade': 3},
{'Name': 'xyz', 'Age': 9, 'Grade': 3}]
df1 = pd.DataFrame(a)
b = [{'ID': 1,'Name': 'abc', 'Age': 8},
{'ID': 2,'Name': 'xyz', 'Age': 9}]
df2 = pd.DataFrame(b)
# Printing Dataframes
display(df1)
display(df2)
# Finding Common columns
a = df2.columns.intersection(df1.columns)
# Printing common columns
print ("Common Columns:",a)
Python3
# Importing libraries
import pandas as pd
# Creating Dataframes
a = [{'Name': 'abc', 'Age': 8, 'Grade': 3},
{'Name': 'xyz', 'Age': 9, 'Grade': 3}]
df1 = pd.DataFrame(a)
b = [{'ID': 1,'Name': 'abc', 'Age': 8},
{'ID': 2,'Name': 'xyz', 'Age': 9}]
df2 = pd.DataFrame(b)
# printing Dataframes
display(df1)
display(df2)
# Finding Common columns
a = df1.columns & df2.columns
# Printing common columns
print ("Common Columns:",a)
输出:
方法二:使用Pandas交集法
在这个例子中,我们将从列表中创建 Pandas Dataframe,然后我们将使用 Panda 的intersection() 方法,该方法将返回两个Dataframes 之间共有的列。
蟒蛇3
# Importing libraries
import pandas as pd
# Creating Dataframes
a = [{'Name': 'abc', 'Age': 8, 'Grade': 3},
{'Name': 'xyz', 'Age': 9, 'Grade': 3}]
df1 = pd.DataFrame(a)
b = [{'ID': 1,'Name': 'abc', 'Age': 8},
{'ID': 2,'Name': 'xyz', 'Age': 9}]
df2 = pd.DataFrame(b)
# Printing Dataframes
display(df1)
display(df2)
# Finding Common columns
a = df2.columns.intersection(df1.columns)
# Printing common columns
print ("Common Columns:",a)
输出:
方法 3:在本例中,我们将使用 &运算符来查找公共列。
蟒蛇3
# Importing libraries
import pandas as pd
# Creating Dataframes
a = [{'Name': 'abc', 'Age': 8, 'Grade': 3},
{'Name': 'xyz', 'Age': 9, 'Grade': 3}]
df1 = pd.DataFrame(a)
b = [{'ID': 1,'Name': 'abc', 'Age': 8},
{'ID': 2,'Name': 'xyz', 'Age': 9}]
df2 = pd.DataFrame(b)
# printing Dataframes
display(df1)
display(df2)
# Finding Common columns
a = df1.columns & df2.columns
# Printing common columns
print ("Common Columns:",a)
输出: