如何用Pandas透视DataFrame并从另一DataFrame补全缺失的disconn时间?
问题描述
现有两个Pandas DataFrame:
table1
| id | time | status |
|---|---|---|
| 1 | 10:00 | conn |
| 1 | 10:01 | disconn |
| 2 | 10:02 | conn |
| 2 | 10:03 | disconn |
| 3 | 10:04 | conn |
table2
| id | time |
|---|---|
| 3 | 10:05 |
需求:当某id在table1中缺少disconn状态的时间值时,从table2中获取对应值,最终得到如下目标结果:
| id | conn | disconn |
|---|---|---|
| 1 | 10:00 | 10:01 |
| 2 | 10:02 | 10:03 |
| 3 | 10:04 | 10:05 |
解决方案
可以通过Pandas的透视表+合并填充的方式快速实现,以下是具体步骤:
步骤1:透视table1生成宽表
先将table1转换为宽表结构,让每个id对应一行,conn和disconn作为列存储对应时间:
import pandas as pd # 构造示例数据(如果已有DataFrame可跳过此部分) table1 = pd.DataFrame({ 'id': [1,1,2,2,3], 'time': ['10:00','10:01','10:02','10:03','10:04'], 'status': ['conn','disconn','conn','disconn','conn'] }) table2 = pd.DataFrame({ 'id': [3], 'time': ['10:05'] }) # 透视转换 pivot_df = table1.pivot(index='id', columns='status', values='time').reset_index() # 清理列名层级 pivot_df.columns.name = None
此时pivot_df的结果为:
| id | conn | disconn |
|---|---|---|
| 1 | 10:00 | 10:01 |
| 2 | 10:02 | 10:03 |
| 3 | 10:04 | NaN |
步骤2:合并table2并填充缺失值
将table2与透视后的表合并,用table2的time值填充disconn列的缺失项:
# 合并两个表 merged_df = pd.merge(pivot_df, table2, on='id', how='left') # 填充disconn的缺失值 merged_df['disconn'] = merged_df['disconn'].fillna(merged_df['time_y']) # 筛选目标列得到最终结果 final_result = merged_df[['id', 'conn', 'disconn']]
简化版代码
如果追求简洁,可以将步骤合并为链式调用:
final_result = (table1.pivot(index='id', columns='status', values='time') .reset_index() .merge(table2, on='id', how='left') .assign(disconn=lambda df: df['disconn'].fillna(df['time'])) .drop(columns=['time']) .rename_axis(None, axis=1))
最终输出
运行代码后,final_result即为目标DataFrame:
| id | conn | disconn |
|---|---|---|
| 1 | 10:00 | 10:01 |
| 2 | 10:02 | 10:03 |
| 3 | 10:04 | 10:05 |
内容的提问来源于stack exchange,提问作者harp1814
相关产品推荐
相关产品推荐

