You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas透视DataFrame并从另一DataFrame补全缺失的disconn时间?

问题描述

现有两个Pandas DataFrame:

table1

idtimestatus
110:00conn
110:01disconn
210:02conn
210:03disconn
310:04conn

table2

idtime
310:05

需求:当某id在table1中缺少disconn状态的时间值时,从table2中获取对应值,最终得到如下目标结果:

idconndisconn
110:0010:01
210:0210:03
310:0410: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的结果为:

idconndisconn
110:0010:01
210:0210:03
310:04NaN

步骤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:

idconndisconn
110:0010:01
210:0210:03
310:0410:05

内容的提问来源于stack exchange,提问作者harp1814

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 06:17:36