6.2 数据连接 (concat) Pandas 数据连接 (concat) 详解 函数的基本用法 函数的基本语法如下: 其中,最常用的参数包括: : 需要连接的 Pandas 对象(Series、DataFrame 或 Panel)的列表或字典。这是必须提供的参数。 : 指定连接的轴。 (默认) 沿行方向连接 (垂直方向,即上下堆叠), 沿列方向连接 (水平方向,即左右拼接)。 : 指定连接方式。 (默认) 执行并集连接,保留所有索引; 执行交集连接,只保留共同的索引。 : 如果为 ,则忽略原始索引,创建一个新的从 0 开始的整数索引。 : 为连接后的数据添加层次化索引,方便区分不同的数据来源。 : 用于设置层次化索引的名称。
concat 函数的基本用法pd.concat() 函数的基本语法如下:
pd.concat(objs, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True)
其中,最常用的参数包括:
objs: 需要连接的 Pandas 对象(Series、DataFrame 或 Panel)的列表或字典。这是必须提供的参数。
axis: 指定连接的轴。axis=0 (默认) 沿行方向连接 (垂直方向,即上下堆叠),axis=1 沿列方向连接 (水平方向,即左右拼接)。
join: 指定连接方式。'outer' (默认) 执行并集连接,保留所有索引;'inner' 执行交集连接,只保留共同的索引。
ignore_index: 如果为 True,则忽略原始索引,创建一个新的从 0 开始的整数索引。
keys: 为连接后的数据添加层次化索引,方便区分不同的数据来源。
names: 用于设置层次化索引的名称。
这是 concat 最常见的用法,用于将多个 DataFrame 或 Series 垂直堆叠起来。
示例 1:连接两个 DataFrame
import pandas as pd # 创建两个 DataFrame df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2']}, index=['K0', 'K1', 'K2']) df2 = pd.DataFrame({'A': ['A3', 'A4', 'A5'], 'B': ['B3', 'B4', 'B5']}, index=['K3', 'K4', 'K5']) # 沿行方向连接 result = pd.concat([df1, df2]) print(result)
输出:
A B K0 A0 B0 K1 A1 B1 K2 A2 B2 K3 A3 B3 K4 A4 B4 K5 A5 B5
示例 2:使用 ignore_index=True 重置索引
result = pd.concat([df1, df2], ignore_index=True) print(result)
输出:
A B 0 A0 B0 1 A1 B1 2 A2 B2 3 A3 B3 4 A4 B4 5 A5 B5
示例 3:使用 keys 添加层次化索引
result = pd.concat([df1, df2], keys=['df1', 'df2']) print(result)
输出:
A B df1 K0 A0 B0 K1 A1 B1 K2 A2 B2 df2 K3 A3 B3 K4 A4 B4 K5 A5 B5
示例 4:使用 names 设置层次化索引的名称
result = pd.concat([df1, df2], keys=['df1', 'df2'], names=['Source', 'Index']) print(result)
输出:
A B Source Index df1 K0 A0 B0 K1 A1 B1 K2 A2 B2 df2 K3 A3 B3 K4 A4 B4 K5 A5 B5
沿列方向连接用于将多个 DataFrame 或 Series 水平拼接起来。
示例 1:连接两个 DataFrame,索引相同
df3 = pd.DataFrame({'C': ['C0', 'C1', 'C2'], 'D': ['D0', 'D1', 'D2']}, index=['K0', 'K1', 'K2']) result = pd.concat([df1, df3], axis=1) print(result)
输出:
A B C D K0 A0 B0 C0 D0 K1 A1 B1 C1 D1 K2 A2 B2 C2 D2
示例 2:连接两个 DataFrame,索引不同,使用 join='outer' (默认)
df4 = pd.DataFrame({'C': ['C3', 'C4', 'C5'], 'D': ['D3', 'D4', 'D5']}, index=['K0', 'K2', 'K3']) result = pd.concat([df1, df4], axis=1) print(result)
输出:
A B C D K0 A0 B0 C3 D3 K1 A1 B1 NaN NaN K2 A2 B2 C4 D4 K3 NaN NaN C5 D5
由于 df1 和 df4 的索引不完全相同,join='outer' 会保留所有索引,并在缺失值处填充 NaN。
示例 3:连接两个 DataFrame,索引不同,使用 join='inner'
result = pd.concat([df1, df4], axis=1, join='inner') print(result)
输出:
A B C D K0 A0 B0 C3 D3 K2 A2 B2 C4 D4
join='inner' 只保留了 df1 和 df4 共同的索引 'K0' 和 'K2'。
concat 同样可以用于连接 Series 对象。
示例 1:连接两个 Series
s1 = pd.Series(['S0', 'S1', 'S2'], name='S1') s2 = pd.Series(['S3', 'S4', 'S5'], name='S2') result = pd.concat([s1, s2]) print(result)
输出:
0 S0 1 S1 2 S2 0 S3 1 S4 2 S5 dtype: object
示例 2:沿列方向连接 Series
result = pd.concat([s1, s2], axis=1) print(result)
输出:
S1 S2 0 S0 S3 1 S1 S4 2 S2 S5
append 方法append 方法是 concat 的一个简化版本,专门用于沿行方向连接 DataFrame 或 Series。
示例 1:使用 append 连接两个 DataFrame
result = df1.append(df2) print(result)
输出与 pd.concat([df1, df2]) 相同。
示例 2:使用 append 连接多个 DataFrame
result = df1.append([df2, df3]) print(result)
verify_integrity 参数verify_integrity 参数用于检查连接后的数据是否包含重复的索引。如果设置为 True 且存在重复索引,则会引发异常。
示例:
df5 = pd.DataFrame({'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2']}, index=['K0', 'K1', 'K0']) # 注意重复索引 K0 try: pd.concat([df1, df5], verify_integrity=True) except ValueError as e: print(f"Error: {e}")
输出:
Error: Indexes have overlapping values: Index(['K0'], dtype='object')
sort 参数sort 参数用于在沿列方向连接时,对连接后的列进行排序。
示例:
df6 = pd.DataFrame({'B': ['B3', 'B4', 'B5'], 'A': ['A3', 'A4', 'A5']}, index=['K0', 'K1', 'K2']) result = pd.concat([df1, df6], axis=1, sort=True) print(result)
输出:
A A B B K0 A0 A3 B0 B3 K1 A1 A4 B1 B4 K2 A2 A5 B2 B5
场景 1:合并多个数据文件
假设你有很多个 CSV 文件,每个文件包含一部分数据,你需要将它们合并成一个大的 DataFrame。
import glob # 假设有三个 CSV 文件:data1.csv, data2.csv, data3.csv csv_files = glob.glob("data*.csv") # 找到所有匹配的文件 # 创建一个空的列表用于存储 DataFrame dfs = [] # 循环读取每个 CSV 文件,并将 DataFrame 添加到列表中 for file in csv_files: df = pd.read_csv(file) dfs.append(df) # 使用 concat 将所有 DataFrame 连接起来 combined_df = pd.concat(dfs, ignore_index=True) # 现在 combined_df 包含了所有 CSV 文件的数据 print(combined_df.head())
场景 2:合并不同来源的数据
假设你从不同的数据库或 API 获取了数据,这些数据包含相同的信息,但存储在不同的 DataFrame 中,你需要将它们合并成一个统一的数据集。
# 假设 df_api 和 df_db 分别是从 API 和数据库获取的 DataFrame combined_df = pd.concat([df_api, df_db], ignore_index=True)
concat 的内部原理 (可选)从技术角度讲,concat 函数在 Pandas 内部依赖于 numpy.concatenate 函数,但是 Pandas 增加了对索引对齐和数据类型的处理。当 axis=0 时,concat 实际上是在行方向上堆叠数据,而当 axis=1 时,它会在列方向上拼接数据。join 参数控制了索引的处理方式,outer 连接会保留所有索引,而 inner 连接只会保留共同的索引。
concat 函数的图形化解释这个 Mermaid 图清晰地展示了 concat 函数在不同轴向上的操作。
pd.concat 是 Pandas 中一个非常重要的函数,它提供了灵活的方式来连接多个 Pandas 对象。通过理解 axis、join、ignore_index、keys 和 names 等参数,你可以根据实际需求灵活地组合数据,从而进行更有效的数据分析和处理。掌握 concat 函数是成为一名熟练的 Pandas 用户的关键一步。