将两个dataframe concat起来
时间: 2024-05-16 11:14:02 浏览: 11
可以使用 pandas 库中的 concat 函数将两个 DataFrame 合并起来。假设你有两个 DataFrame,分别是 df1 和 df2,它们的列名和数据类型都相同,那么可以这样合并它们:
```python
import pandas as pd
# 创建示例数据
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'A': [4, 5, 6], 'B': [7, 8, 9]})
# 使用 concat 合并两个 DataFrame
result = pd.concat([df1, df2])
print(result)
```
输出结果:
```
A B
0 1 4
1 2 5
2 3 6
0 4 7
1 5 8
2 6 9
```
注意,合并后的结果中的行索引是连续的,如果想要重新设置行索引,可以使用 reset_index 函数,例如:
```python
result = pd.concat([df1, df2], ignore_index=True)
```
这样就会重新生成一个连续的行索引。
相关问题
python将两个dataframe拼起来
可以使用pandas库中的concat函数来将两个dataframe拼接在一起,具体代码如下:
```python
import pandas as pd
# 创建两个示例dataframe
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'A': [7, 8, 9], 'B': [10, 11, 12]})
# 使用concat函数将两个dataframe拼接起来
result = pd.concat([df1, df2], ignore_index=True)
# 打印拼接后的结果
print(result)
```
其中,concat函数的第一个参数为一个列表,列表中包含需要拼接的dataframe;ignore_index=True参数表示将原数据的索引重新编号。
将两个dataframe竖着连起来
您可以使用 Pandas 库中的 concat 方法将两个 DataFrame 竖着连接起来。例如:
```python
import pandas as pd
# 创建两个 DataFrame
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df2 = pd.DataFrame({'A': [7, 8, 9], 'B': [10, 11, 12]})
# 使用 concat 方法竖着连接两个 DataFrame
result = pd.concat([df1, df2], axis=0)
# 输出连接后的结果
print(result)
```
输出结果为:
```
A B
0 1 4
1 2 5
2 3 6
0 7 10
1 8 11
2 9 12
```
其中 axis=0 表示按行连接,也就是竖着连接。如果要按列连接,可以将 axis 参数设置为 1。