Python - 根据交集获取两个 Pandas DataFrames 之间的列
要根据交集获取两个 DataFrames 之间的列,请使用 intersection() 方法。让我们创建两个 DataFrames −
# creating dataframe1 dataFrame1 = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000], }) # creating dataframe2 dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90] })
获取公共列 −
dataFrame2.columns.intersection(dataFrame1.columns)
示例
以下是完整的代码 −
import pandas as pd # creating dataframe1 dataFrame1 = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000], }) 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 intersection() res = dataFrame2.columns.intersection(dataFrame1.columns) print"\nCommon columns...\n",res
输出
这将产生以下输出 −
Dataframe1... Car Cubic_Capacity Reg_Price 0 Bentley 2000 7000 1 Lexus 1800 1500 2 Tesla 1500 5000 3 Mustang 2500 8000 4 Mercedes 2200 9000 5 Jaguar 3000 6000 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')
广告