[英]pandas pivot columns to rows
I have a dataframe such as the one below that I pivoted to apply some operations on. 我有一个数据框(例如下面的数据框),我对其进行了枢转以对其进行一些操作。
Original dataframe df: 原始数据框df:
index item value day time
0 P472 0.126 2011-12-08 00:00:00
1 P472 0.12 2011-12-08 00:30:00
2 P472 0.119 2011-12-08 01:00:00
3 P472 0.425 2011-12-08 01:30:00
4 P472 0.154 2011-12-08 02:00:00
I pivoted the dataframe with code below to produce the new dataframe below: 我使用下面的代码对数据框进行了透视,以产生下面的新数据框:
df_pivoted = df.pivot_table(index=['item', 'day'], columns='time',
values='value', aggfunc='first').reset_index()
df_pivoted: df_pivoted:
index item day 00:00:00 00:30:00 ... 23:30:00
0 P472 2011-12-08 0.126 0.12 ... 0.18
1 P473 2011-12-08 0.5 0.55 ... 0.30
Now I want to re-pivot df_pivoted to be in the layout of the original dataframe, ie collapse columns 00:00:00 through 23:30:00 to a time column, each 24 hour time within a specific day, and re-introducing the value column (using df_pivoted.stack?) but I cant work out how to do this. 现在,我想将df_pivoted重新设置为原始数据帧的布局,即将00:00:00到23:30:00的列折叠到时间列,在特定的一天中每个24小时时间,然后重新引入值列(使用df_pivoted.stack?),但我无法解决如何做到这一点。 Any ideas>?
任何想法>?
The reverse of pd.pivot_table
can be achieved via pd.melt
: pd.pivot_table
的相反pd.pivot_table
可以通过pd.melt
实现:
df_melted = df_pivoted.melt(id_vars=['index', 'item', 'day', 'time'],
value_vars=['value']).drop('variable', 1)
print(df)
index item value day time
0 0 P472 0.126 2011-12-08 00:00:00
1 1 P472 0.120 2011-12-08 00:30:00
2 2 P472 0.119 2011-12-08 01:00:00
3 3 P472 0.425 2011-12-08 01:30:00
4 4 P472 0.154 2011-12-08 02:00:00
It's worth pointing out this works because your aggregation function is 'first'
and combinations of ['index', 'item', 'day', 'time']
are unique. 值得指出的是,此功能有效,因为您的聚合函数是
'first'
并且['index', 'item', 'day', 'time']
是唯一的。 If they were not, then the pivot table would be aggregating data and losing information which cannot be put together again. 如果不是,则数据透视表将聚集数据并丢失无法再次放在一起的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.