Pandas 数据合并:concat 函数详解与实例
Pandas 数据合并:concat 函数详解与实例
在使用 Pandas 进行数据分析时,我们经常需要将多个 DataFrame 对象合并成一个 DataFrame。Pandas 提供了 concat 函数来实现这一功能。
concat 函数语法
pandas.concat(objs, axis=0, join='outer', ignore_index=False)
参数说明
objs:要连接的 DataFrame 对象序列,可以是 DataFrame、Series 或者是 DataFrame 的列表。axis:指定连接的轴方向,取值为 0 或 1,默认为 0,表示按行连接。join:指定连接的方式,取值为 'outer' 或 'inner',默认为 'outer',表示取并集。ignore_index:指定是否忽略原始索引,取值为 True 或 False,默认为 False,表示保留原始索引。
concat 函数应用实例
1. 按行连接两个 DataFrame 对象
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})
result = pd.concat([df1, df2])
print(result)
输出结果:
A B
0 1 3
1 2 4
0 5 7
1 6 8
2. 按列连接两个 DataFrame 对象
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'C': [5, 6], 'D': [7, 8]})
result = pd.concat([df1, df2], axis=1)
print(result)
输出结果:
A B C D
0 1 3 5 7
1 2 4 6 8
3. 忽略原始索引
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=[0, 1])
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]}, index=[2, 3])
result = pd.concat([df1, df2], ignore_index=True)
print(result)
输出结果:
A B
0 1 3
1 2 4
2 5 7
3 6 8
4. 按内连接方式连接两个 DataFrame 对象
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [2, 3], 'B': [4, 5]})
result = pd.concat([df1, df2], join='inner')
print(result)
输出结果:
A B
1 2 4
通过上述示例,我们可以看到 concat 函数可以灵活地合并 DataFrame 数据。在实际应用中,我们可以根据需要选择不同的参数来实现不同的数据合并效果。
原文地址: http://www.cveoy.top/t/topic/dUvY 著作权归作者所有。请勿转载和采集!