Python DataFrame 如何将每隔n行的列值转置为新增列
Pandas 交替时间行配对并排展示方案
需求
现有交替排列的时间行数据,Name、Value列存在冗余,仅需保留Time列取值,将配对的两个时间值并排存入新列,实现行合并。
原始数据说明
处理前DataFrame共6行,包含索引、Name、Time、Value、Value2五列:
- 索引0:Name=Q,Time=09:15,Value=1,Value2为空
- 索引1:Name=Q,Time=09:16,Value=0,Value2为空
- 索引2:Name=Q,Time=09:18,Value=1,Value2为空
- 索引3:Name=Q,Time=09:19,Value=0,Value2为空
- 索引4:Name=P,Time=22:30,Value=1,Value2为空
- 索引5:Name=P,Time=23:20,Value=0,Value2为空
目标结果
合并后共3行,每2行原始数据合并为1行:保留Value=1行的Name、Time、Value字段,将同组配对的Value=0行的Time值填入Value2列:
- 索引0:Name=Q,Time=09:15,Value=1,Value2=09:16
- 索引1:Name=Q,Time=09:18,Value=1,Value2=09:19
- 索引2:Name=P,Time=22:30,Value=1,Value2=23:20
注:原需求描述中P组Time写为23:20为笔误,按数据逻辑修正为Value=1对应的22:30
实现代码
不需要复杂转置操作,如果数据严格按1、0交替排列,直接筛选赋值即可,代码最简洁:
import pandas as pd # 构造示例原始数据 df = pd.DataFrame({ 'Name': ['Q', 'Q', 'Q', 'Q', 'P', 'P'], 'Time': ['09:15', '09:16', '09:18', '09:19', '22:30', '23:20'], 'Value': [1, 0, 1, 0, 1, 0], 'Value2': [None]*6 }) # 核心处理:筛选Value=1的行,将Value=0的Time按顺序赋值给Value2 result = df[df['Value'] == 1].reset_index(drop=True) result['Value2'] = df[df['Value'] == 0]['Time'].values
如果数据存在同组内1、0顺序不固定的情况,可以用分组方式适配,兼容性更强:
# 分组兼容版:按Name分组,组内每2行自动配对 result = ( df.groupby('Name', group_keys=False) .apply(lambda x: x.assign(Value2=x['Time'].shift(-1))) .query('Value == 1') .reset_index(drop=True) )
内容的提问来源于stack exchange,提问作者zestytestful
相关产品推荐
相关产品推荐

