如何将单行Pandas DataFrame转换为多行结构化DataFrame?
Pandas 宽表转长表解决方案
可以用Pandas的pd.wide_to_long函数快速实现这个转换,这是专门针对这类带序号前缀列的宽表转长表场景的简便方法,步骤如下:
步骤1:统一列名格式
先把原DataFrame中对应分组的列名改成「前缀_序号」的统一格式,让需要配对的列对应相同序号:
# 修改列名 df_1D = df_1D.rename(columns={ 'Destination_A': 'Destination_1', 'Destination_B': 'Destination_2', 'Destination_C': 'Destination_3', 'First_Agent': 'Agent_1', 'Second_Agent': 'Agent_2', 'Third_Agent': 'Agent_3' })
步骤2:使用wide_to_long转换
指定不需要转换的标识列(ID、Country),再定义需要展开的列前缀,自动按序号配对:
import pandas as pd # 执行转换 result = pd.wide_to_long(df_1D, stubnames=['Day', 'Destination', 'Agent'], i=['ID', 'Country'], j='drop_col', # 临时列名,后续会删除 sep='_', suffix=r'\d+').reset_index() # 整理结果,删除临时列并调整列顺序 result = result.drop('drop_col', axis=1)[['Day', 'ID', 'Country', 'Destination', 'Agent']]
转换结果
执行后得到的result就是目标格式:
Day ID Country Destination Agent 0 5 AB12 US Miami Jim 1 6 AB12 US New York Ron 2 7 AB12 US Chicago Cynthia
内容的提问来源于stack exchange,提问作者the phoenix
相关产品推荐
相关产品推荐

