如何基于指定键合并两个DataFrame并保留原列名?
按date合并DataFrame并保留原列结构的解决方法
原始数据
df1
| date | location | earthquake | rain |
|---|---|---|---|
| 01-Feb-2022 | US. | 1. | 2. |
| 02-Feb-2022 | US. | 3. | 4. |
| 03-Feb-2022 | US. | 5. | 6. |
df2
| date. | location | earthquake | rain |
|---|---|---|---|
| 01-Feb-2022 | Canada | 7. | 8. |
| 03-Feb-2022 | Canada. | 9. | 10. |
| 04-Feb-2022 | US. | 11. | 12. |
问题
你用merge尝试合并:
df1.merge(df2, how='inner', on='date')
得到的结果是横向合并同date的行,列名自动加了后缀,不符合预期:
| date | location_1 | earthquake_1 | rain_1 | location_2 | earthquake_2 | rain_2 |
|---|---|---|---|---|---|---|
| 01-Feb-2022 | US | 1 | 2 | Canada | 7 | 8 |
| 03-Feb-2022 | US | 5 | 6 | Canada | 9 | 10 |
你想要的是保留原列结构,把同date的行纵向排列:
| date | location | earthquake | rain |
|---|---|---|---|
| 01-Feb-2022 | US | 1. | 2. |
| 01-Feb-2022 | Canada. | 7. | 8. |
| 03-Feb-2022 | US. | 5. | 6. |
| 03-Feb-2022 | Canada. | 9. | 10. |
解决方法
你用错工具了——merge是做横向关联匹配的,而你需要的是纵向拼接符合条件的行。步骤如下:
- 先把df2的
date.列名改成date,统一键名:
df2 = df2.rename(columns={'date.': 'date'})
- 找出两个数据集共有的date值:
common_dates = df1['date'].intersection(df2['date'])
- 分别筛选两个df中属于共有date的行,再拼接起来,最后按date排序:
import pandas as pd filtered_df1 = df1[df1['date'].isin(common_dates)] filtered_df2 = df2[df2['date'].isin(common_dates)] result = pd.concat([filtered_df1, filtered_df2]).sort_values('date').reset_index(drop=True)
运行这段代码后,result就是你要的输出。
补充说明
concat用来纵向堆叠行,能完美保留原列结构,不会生成带后缀的列。- 筛选共有date是为了实现类似
inner的效果,只保留两个df都存在的日期数据。 sort_values('date')让同日期的行排在一起,reset_index重置索引避免混乱。
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

