Python Pandas – 是否可以使用 & 操作符查找两个 DataFrame 之间的公共列?
是的,我们可以使用 & 运算符来查找两个 DataFrame 之间的公共列。首先,让我们创建两个 DataFrame -
# creating dataframe1 dataFrame1 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000], }) print("Dataframe1...\n",dataFrame1) # creating dataframe2 dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90] })
使用 & 运算符获取公共列 -
res = dataFrame1.columns & dataFrame2.columns
示例
以下为代码 -
import pandas as pd # creating dataframe1 dataFrame1 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000], }) print"Dataframe1...\n",dataFrame1 # creating dataframe2 dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90] }) print"Dataframe2...\n",dataFrame2 # getting common columns using the & operator res = dataFrame1.columns & dataFrame2.columns print"\nCommon columns...\n",res
输出
这将产生以下输出 -
Dataframe1... Car Cubic_Capacity 0 BMW 2000 1 Lexus 1800 2 Tesla 1500 3 Mustang 2500 4 Mercedes 2200 5 Jaguar 3000 Dataframe2... Car Units_Sold 0 BMW 100 1 Lexus 110 2 Tesla 150 3 Mustang 80 4 Mercedes 200 5 Jaguar 90 Common columns... Index([u'Car'], dtype='object')
广告