将 Pandas DataFrame 与公共列合并
要将两个具有公共列的 Pandas DataFrame 合并,请使用该merge()函数并将ON参数设置为列名。
首先,让我们使用别名导入 pandas 库 -
import pandas as pd
让我们创造1日数据框-
dataFrame1 = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
}
)
接下来,创建第二个DataFrame -
dataFrame2 = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
}
)
现在,将两个 DataFrame 与列“Car”合并 -
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car')
示例
以下是完整的代码 -
import pandas as pd输出结果# Create DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
}
)
print"DataFrame1 ...\n",dataFrame1
# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# merge DataFrames with common column Car
mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car')
print"\nMerged data frame with common column...\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 Audi 5000
3 Mustang 8000
4 Mercedes 9000
5 Jaguar 6000
Merged data frame with common column...
Car Units Reg_Price
0 BMW 100 7000
1 Lexus 150 1500
2 Audi 110 5000
3 Mustang 80 8000
4 Jaguar 90 6000
以上是 将 Pandas DataFrame 与公共列合并 的全部内容, 来源链接: utcz.com/z/338708.html