Python Pandas - 合并和创建两个 DataFrame 的笛卡尔积
要合并 Pandas DataFrame,请使用 merge() 函数。笛卡尔积通过在 merge() 函数的“how”参数下设置这两个 DataFrame 来实现,即 -
how = “cross”
首先,让我们导入 pandas 库并使用别名 -
import pandas as pd
创建 DataFrame1 -
dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 120] } )
创建 DataFrame2
dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Tesla', 'Jaguar'],"Reg_Price": [7000, 8000, 9000] } )
接下来,在 "how" 参数中使用 "cross" 合并 DataFrame 即。笛卡尔积 -
mergedRes = pd.merge(dataFrame1, dataFrame2, how ="cross")
示例
以下是代码
import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 120] } ) print("DataFrame1 ...\n",dataFrame1) # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Tesla', 'Jaguar'],"Reg_Price": [7000, 8000, 9000] } ) print("\nDataFrame2 ...\n",dataFrame2) # merge DataFrames with "cross" in "how" parameter i.e Cartesian Product mergedRes = pd.merge(dataFrame1, dataFrame2, how ="cross") print("\nMerged dataframe with cartesian product...\n", mergedRes)
输出
这将产生以下输出 -
DataFrame1 ... Car Units 0 BMW 100 1 Mustang 150 2 Bentley 110 3 Jaguar 120 DataFrame2 ... Car Reg_Price 0 BMW 7000 1 Tesla 8000 2 Jaguar 9000 Merged dataframe with cartesian product... Car Units Car_y Reg_Price 0 BMW 100 BMW 7000 1 BMW 100 Tesla 8000 2 BMW 180 Jaguar 9000 3 Mustang 150 BMW 7000 4 Mustang 150 Tesla 8000 5 Mustang 150 Jaguar 9000 6 Bentley 110 BMW 7000 7 Bentley 110 Tesla 8000 8 Bentley 110 Jaguar 9000 9 Jaguar 120 BMW 7000 10 Jaguar 120 Tesla 8000 11 Jaguar 120 Jaguar 9000
广告