如何将多个dataframe按照两个索引合并
时间: 2023-03-27 08:04:45 浏览: 110
您可以使用 pandas 的 merge 函数来将多个 dataframe 按照两个索引合并。具体操作如下:
```python
import pandas as pd
# 创建多个 dataframe
df1 = pd.DataFrame({'key1': ['A', 'B', 'C', 'D'], 'key2': ['X', 'Y', 'Z', 'W'], 'value1': [1, 2, 3, 4]})
df2 = pd.DataFrame({'key1': ['A', 'B', 'C', 'D'], 'key2': ['X', 'Y', 'Z', 'W'], 'value2': [5, 6, 7, 8]})
df3 = pd.DataFrame({'key1': ['A', 'B', 'C', 'D'], 'key2': ['X', 'Y', 'Z', 'W'], 'value3': [9, 10, 11, 12]})
# 将多个 dataframe 按照两个索引合并
merged_df = pd.merge(df1, df2, on=['key1', 'key2']).merge(df3, on=['key1', 'key2'])
# 打印合并后的 dataframe
print(merged_df)
```
输出结果如下:
```
key1 key2 value1 value2 value3
A X 1 5 9
1 B Y 2 6 10
2 C Z 3 7 11
3 D W 4 8 12
```
阅读全文