Python Pandas – 从两个 DataFrames 合并并创建笛卡尔积
要合并 Pandas DataFrame,请使用该merge()函数。通过在函数的“如何”参数下设置,笛卡尔积在两个数据帧上实现,merge()即 -
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]
}
)
接下来,将 DataFrames 与“how”参数中的“cross”合并,即笛卡尔积 -
mergedRes = pd.merge(dataFrame1, dataFrame2, how ="cross")
示例
以下是代码
import pandas as pd输出结果# 创建 DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 120]
}
)
print("DataFrame1 ...\n",dataFrame1)
# 创建 DataFrame2
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Tesla', 'Jaguar'],"Reg_Price": [7000, 8000, 9000]
}
)
print("\nDataFrame2 ...\n",dataFrame2)
# merge DataFrames with "cross" in "how" parameteri.eCartesian 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
以上是 Python Pandas – 从两个 DataFrames 合并并创建笛卡尔积 的全部内容, 来源链接: utcz.com/z/359947.html