Python Pandas – 查找两个数据帧之间的公共行
如需查找两个 DataFrame 之间的公共行,请使用 merge() 方法。我们先使用两列创建 DataFrame1,如下所示:
dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } )
使用两列创建 DataFrame2,如下所示:
dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'], "Units": [100, 250, 150, 80, 130, 90] } )
如需查找公共行,请执行以下操作:
dataFrame1.merge(dataFrame2, how = 'inner' ,indicator=False)
示例
以下是代码:
import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } ) print"DataFrame1 ...\n",dataFrame1 # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'], "Units": [100, 250, 150, 80, 130, 90] } ) print"\nDataFrame2 ...\n",dataFrame2 # check for equality print"\nAre both the DataFrames equal? ",dataFrame1.equals(dataFrame2) # finding common rows between two DataFrames resData = dataFrame1.merge(dataFrame2, how = 'inner' ,indicator=False) print"\nCommon rows between two DataFrames...\n",resData
输出
这将产生以下输出:
DataFrame1 ... Car Units 0 BMW 100 1 Lexus 150 2 Audi 110 3 Tesla 80 4 Bentley 110 5 Jaguar 90 DataFrame2 ... Car Units 0 BMW 100 1 Lexus 250 2 Audi 150 3 Mustang 80 4 Bentley 130 5 Jaguar 90 Are both the DataFrames equal? False Common rows between two DataFrames... Car Units 0 BMW 100 1 Jaguar 90
广告