python使用concat合并dataframe
时间: 2024-12-11 07:40:16 浏览: 24
Python中的`pandas`库提供了多种方法来合并DataFrames,其中`pd.concat()`是最常用的一种。这里有两个示例:
1. **基本合并**[^1]:
```python
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'C': [5, 6], 'D': [7, 8]})
# 沿着列(默认)方向合并
result = pd.concat([df1, df2])
print(result)
```
这将把`df1`和`df2`的数据按列堆叠在一起。
2. **指定轴(axis)**:
如果你想沿着行方向合并(axis=0),可以这样做:
```python
result = pd.concat([df1, df2], axis=0)
```
3. **使用keys进行多级索引合并**[^2]:
```python
dfs = [pd.DataFrame({'key': ['K0', 'K0', 'K1', 'K2'],
'A': ['A0', 'A1', 'A2', 'A3']}),
pd.DataFrame({'key': ['K0', 'K1', 'K1', 'K2'],
'B': ['B0', 'B1', 'B2', 'B3']})]
result = pd.concat(dfs, keys=['table1', 'table2'])
print(result)
```
这里创建了一个多级索引,通过`keys`参数指定每个DataFrame所属的组。
阅读全文
相关推荐


















