Python - 将 Pandas DataFrame 与右外连接合并
要合并 Pandas DataFrame,请使用该merge()函数。通过在函数的“如何”参数下设置,在两个数据帧上实现右外连接,merge()即 -
how = “right”
首先,让我们使用别名导入 pandas 库 -
import pandas as pd
创建两个要合并的数据框 -
# 创建 DataFrame1dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
}
)
# 创建 DataFrame2
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
}
)
将 DataFrames 与公共列 Car 和“how”参数中的“right”合并实现 Right Outer Join -
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="right")
示例
以下是代码 -
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 common column Car and "right" in "how" parameter implements Right Outer Join
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="right")
print"\nMerged dataframe with right outer join...\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 right outer join...
Car Units Reg_Price
0 BMW 100.0 7000
1 Lexus 150.0 1500
2 Mustang 80.0 8000
3 Jaguar 90.0 6000
4 Tesla NaN 5000
5 Mercedes NaN 9000
以上是 Python - 将 Pandas DataFrame 与右外连接合并 的全部内容, 来源链接: utcz.com/z/335501.html