Python - 使用 Numpy 获取两个 Pandas DataFrame 共享的列
要获取两个DataFrame共享的列,请使用intersect1d()方法。此方法由numpy提供,因此您还需要使用Pandas导入Numpy。让我们首先导入所需的库-
import pandas as pd import numpy as np
创建两个数据帧-
#创建数据框1 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],"Units_Sold": [ 100, 110, 150, 80, 200, 90] }) #创建数据框2 dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90] })
使用numpy方法intersect1获取公共列d()-
res = np.intersect1d(dataFrame2.columns, dataFrame1.columns)
示例
以下是代码-
import pandas as pd import numpy as np #创建数据框1 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],"Units_Sold": [ 100, 110, 150, 80, 200, 90] }) print"Dataframe1...\n",dataFrame1 #创建数据框2 dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90] }) print"Dataframe2...\n",dataFrame2 #使用intersect1d()获取公共列 res = np.intersect1d(dataFrame2.columns, dataFrame1.columns) print"\nCommon columns...\n",res输出结果
这将产生以下输出-
Dataframe1... Car Cubic_Capacity Reg_Price Units_Sold 0 Bentley 2000 7000 100 1 Lexus 1800 1500 110 2 Tesla 1500 5000 150 3 Mustang 2500 8000 80 4 Mercedes 2200 9000 200 5 Jaguar 3000 6000 90 Dataframe2... Car Units_Sold 0 BMW 100 1 Lexus 110 2 Tesla 150 3 Mustang 80 4 Mercedes 200 5 Jaguar 90 Common columns... ['Car' 'Units_Sold']