使用熊猫将数据帧从长到宽转换-单行输出

问题描述 投票:1回答:1

我有一个如下所示的数据框

df = pd.DataFrame({
'subject_id':[1,1,1,1,2,2,2,2],
'date':['2173/04/11','2173/04/12','2173/04/11','2173/04/12','2173/05/14','2173/05/15','2173/05/14','2173/05/15'],
'time_1':['2173/04/11 12:35:00','2173/04/12 12:50:00','2173/04/11 12:59:00','2173/04/12 13:14:00','2173/05/14 13:37:00','2173/05/15 13:39:00','2173/05/14 18:37:00','2173/05/15 19:39:00'],
 'val' :[5,5,40,40,7,7,38,38],
 'iid' :[12,12,12,12,21,21,21,21]   
 })
df['time_1'] = pd.to_datetime(df['time_1'])
df['day'] = df['time_1'].dt.day

我尝试使用stack,unstack,pivot and melt方法,但似乎没有帮助

pd.melt(df, id_vars =['subject_id','val'], value_vars =['date','val']) #1

df.unstack().reset_index()  #2

df.pivot(index='subject_id', columns='time_1', values='val')  #3 

我希望我的输出数据帧看起来如下图所示

enter image description here

更新的屏幕截图

enter image description here

enter image description here

python python-3.x pandas dataframe transformation
1个回答
1
投票

[想法是通过GroupBy.cumcount创建帮助器系列,具有用于新索引的相同列/列-在这里GroupBy.cumcount,创建subject_id,通过MultiIndex整形并最后展平DataFrame.unstack

DataFrame.unstack
© www.soinside.com 2019 - 2024. All rights reserved.