【零基础玩转Python】Day44:数据合并 – concat, merge, join,像SQL一样关联多张表
大家好,我是[知识充电宝的灵感日记]。
在实际工作中,数据往往分散在多个文件或表格中。比如:订单信息在一张表,用户信息在另一张表。今天我们将学习三种合并数据的方法:concat(简单拼接)、merge(类似 SQL 的关联)、join(基于索引的合并)。掌握它们,你就能像数据库一样整合数据。
今天的目标:
- ✅ merge:基于列的关联合并(一对一、一对多、多对多)
- ✅ join:基于索引的合并(merge 的便捷版本)
难度:⭐⭐⭐(需要理解连接类型,但类比 SQL 很容易)
一、准备工作
import pandas as pd
二、concat():简单拼接
concat 用于将多个 DataFrame 沿轴向堆叠。
1. 纵向拼接(行拼接,axis=0 默认)
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
索引会重复,可重置索引:
result = pd.concat([df1, df2], ignore_index=True)
2. 横向拼接(列拼接,axis=1)
df3 = pd.DataFrame({'C': [9, 10], 'D': [11, 12]})
result = pd.concat([df1, df3], axis=1)
print(result)
# A B C D
# 0 1 3 9 11
# 1 2 4 10 12
A B C D
0 1 3 9 11
1 2 4 10 12
3. 处理列不匹配(默认缺失处补 NaN)
df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'C': [7, 8]})
result = pd.concat([df1, df2], ignore_index=True)
print(result)
# A B C
# 0 1 3.0 NaN
# 1 2 4.0 NaN
# 2 5 NaN 7.0
# 3 6 NaN 8.0
三、merge():类似 SQL 的关联合并
merge 根据一个或多个键将两个 DataFrame 的行连接起来,用法类似 SQL 的 JOIN。
1. 一对一合并(基于共同列)
df_users = pd.DataFrame({
'user_id': [1, 2, 3],
'name': ['张三', '李四', '王五']
})
df_orders = pd.DataFrame({
'user_id': [1, 2, 2, 3],
'amount': [100, 200, 150, 300]
})
result = pd.merge(df_users, df_orders, on='user_id')
print(result)
# user_id name amount
# 0 1 张三 100
# 1 2 李四 200
# 2 2 李四 150
# 3 3 王五 300
默认是 how='inner'(内连接),只保留两个表都有的键。
2. 连接类型(how 参数)
# 左连接:保留所有用户,即使没有订单
result = pd.merge(df_users, df_orders, on='user_id', how='left')
print(result)
# user_id name amount
# 0 1 张三 100.0
# 1 2 李四 200.0
# 2 2 李四 150.0
# 3 3 王五 300.0
3. 多列作为连接键
df1 = pd.DataFrame({'key1': [1,1,2], 'key2': ['a','b','a'], 'value': [10,20,30]})
df2 = pd.DataFrame({'key1': [1,2], 'key2': ['a','a'], 'value2': [100,200]})
result = pd.merge(df1, df2, on=['key1', 'key2'])
print(result)
key1 key2 value value2
0 1 a 10 100
1 2 a 30 200
4. 列名不同时的连接
df_left = pd.DataFrame({'id': [1,2], 'name': ['A','B']})
df_right = pd.DataFrame({'user_id': [1,3], 'score': [90,80]})
result = pd.merge(df_left, df_right, left_on='id', right_on='user_id')
print(result)
# id name user_id score
# 0 1 A 1 90
四、join():基于索引的合并
join 是 merge 的便捷版,默认按索引连接。
df_left = pd.DataFrame({'A': [1,2]}, index=[1,2])
df_right = pd.DataFrame({'B': [3,4]}, index=[2,3])
result = df_left.join(df_right, how='inner')
print(result)
# A B
# 2 2 3
等价于 pd.merge(df_left, df_right, left_index=True, right_index=True, how='inner')。
五、实战小案例
案例1:用户与订单分析
# 用户表
users = pd.DataFrame({
'uid': [1,2,3,4],
'name': ['张三','李四','王五','赵六'],
'city': ['北京','上海','北京','广州']
})
# 订单表
orders = pd.DataFrame({
'uid': [1,2,2,3,5],
'order_id': [101,102,103,104,105],
'amount': [150,200,100,250,300]
})
# 1. 内连接:有订单的用户及其订单
inner_join = pd.merge(users, orders, on='uid', how='inner')
print("内连接:\n", inner_join)
# 2. 左连接:所有用户,订单信息缺失的为 NaN
left_join = pd.merge(users, orders, on='uid', how='left')
print("左连接:\n", left_join)
# 3. 按用户统计总订单金额(分组聚合)
total = pd.merge(users, orders, on='uid', how='left').groupby('uid').agg({'amount': 'sum', 'name': 'first'})
print(total)
内连接:
uid name city order_id amount
0 1 张三 北京 101 150
1 2 李四 上海 102 200
2 2 李四 上海 103 100
3 3 王五 北京 104 250
左连接:
uid name city order_id amount
0 1 张三 北京 101.0 150.0
1 2 李四 上海 102.0 200.0
2 2 李四 上海 103.0 100.0
3 3 王五 北京 104.0 250.0
4 4 赵六 广州 NaN NaN
amount name
uid
1 150.0 张三
2 300.0 李四
3 250.0 王五
4 0.0 赵六
案例2:横向拼接不同数据源
df_sales = pd.DataFrame({'month': [1,2,3], 'revenue': [100,200,150]})
df_expense = pd.DataFrame({'month': [1,2,3], 'cost': [70,110,80]})
# 按月份合并
result = pd.merge(df_sales, df_expense, on='month')
result['profit'] = result['revenue'] - result['cost']
print(result)
month revenue cost profit
0 1 100 70 30
1 2 200 110 90
2 3 150 80 70
案例3:多表拼接(concat 处理)
# 不同月份的销售数据,列结构相同
jan = pd.DataFrame({'product': ['A','B'], 'sales': [100,80]})
feb = pd.DataFrame({'product': ['A','B'], 'sales': [120,90]})
mar = pd.DataFrame({'product': ['A','C'], 'sales': [110,70]})
# 纵向拼接
all_sales = pd.concat([jan, feb, mar], ignore_index=True)
print(all_sales)
product sales
0 A 100
1 B 80
2 A 120
3 B 90
4 A 110
5 C 70
六、今日练习
df_a = pd.DataFrame({'id': [1,2,3], 'name': ['A','B','C']})
df_b = pd.DataFrame({'id': [2,3,4], 'score': [90,80,70]})
分别用内连接、左连接、右连接、外连接合并,观察结果行数。
- 用 concat 横向拼接两个 DataFrame:
df_x = pd.DataFrame({'x': [1,2]})
df_y = pd.DataFrame({'y': [3,4]})
emp = pd.DataFrame({'dept_id': [1,1,2,3], 'emp_name': ['张三','李四','王五','赵六']})
dept = pd.DataFrame({'dept_id': [1,2,4], 'dept_name': ['技术部','销售部','市场部']})
用左连接找出每个员工所属的部门名(没有部门的显示 NaN)。
df1 = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv')df2 = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv')(相同数据,仅作练习)
模拟拆分后合并:将 df1 和 df2 纵向拼接,然后重置索引。
七、常见错误与提示
concat默认复制索引:使用 ignore_index=True重置索引。merge默认内连接:根据实际业务需求选择 how参数。- 重复列名:合并后同名列会自动添加
_x、_y后缀,可通过 suffixes参数自定义。 merge时未指定 on:会按两表列名交集自动连接,易产生非预期结果,建议显式指定连接键。join基于索引连接:若需要按列连接,使用 merge更合适。- 大数据集合并:确保连接键已排序,或设置
sort=False提升合并性能。
八、明日预告
Day45:时间序列基础 – to_datetime, resample
我们将学习 Pandas 处理时间序列的强大功能,包括日期解析、数据重采样等核心操作。