Python Pandas – 使用一对多关系合并 DataFrame
要合并PandasDataFrame,请使用该merge()函数。在一个一对多的关系是通过在“设置上都DataFrames实施验证了”参数merge()的功能,即-
validate = “one-to-many” or validate = “1:m”
一对多关系检查合并键在左侧数据集中是否唯一。
首先,让我们创建我们的第一个DataFrame-
dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] } )
现在,让我们创建我们的第二个DataFrame-
dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000] } )
示例
以下是代码-
import pandas as pd #创建DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] } ) print("DataFrame1 ...\n",dataFrame1) #创建DataFrame2 dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000] } ) print("\nDataFrame2 ...\n",dataFrame2) # merge DataFrames with "one-to-many" in "validate" parameter mergedRes = pd.merge(dataFrame1, dataFrame2, validate ="one_to_many") print("\nMerged dataframe with one-to-many relation...\n", mergedRes)输出结果
这将产生以下输出-
DataFrame1 ... Car Units 0 BMW 100 1 Lexus 150 2 Audi 110 3 Mustang 80 4 Bentley 110 5 Jaguar 90 DataFrame2 ... Car Reg_Price 0 BMW 7000 1 Lexus 1500 2 Tesla 5000 3 Mustang 8000 4 Mercedes 9000 5 Jaguar 6000 Merged dataframe with one-to-many realtion ... Car Units Reg_Price 0 BMW 100 7000 1 Lexus 150 1500 2 Mustang 80 8000 3 Jaguar 90 6000