[英]Data to pivot table
數據包含
timeslot Weather Location Slot
2014-10-26 00:00 35 1 1
2014-10-26 06:00 36 1 2
2014-10-26 12:00 34 1 3
2014-10-26 18:00 34 1 4
2014-10-27 00:00 35 1 1
2014-10-27 06:00 36 1 2
2014-10-27 12:00 36 1 3
2014-10-27 18:00 32 1 4
2014-10-28 00:00 35 1 1
2014-10-28 06:00 33 1 2
2014-10-28 12:00 35 1 3
2014-10-28 18:00 33 1 4
2014-10-26 00:00 45 2 1
2014-10-26 06:00 46 2 2
2014-10-26 12:00 41 2 3
2014-10-26 18:00 39 2 4
2014-10-27 00:00 46 2 1
2014-10-27 06:00 44 2 2
2014-10-27 12:00 45 2 3
2014-10-27 18:00 42 2 4
2014-10-28 00:00 41 2 1
2014-10-28 06:00 40 2 2
2014-10-28 12:00 42 2 3
2014-10-28 18:00 41 2 4
數據包含兩個定位點的天氣。 每天的停留時間轉換為6小時的時間段。 我想將數據轉換為數據透視表。
我試過的代碼是
df.pivot(index='Location', columns='Timeslot', values='weather')
輸出應為:
Timeslot 2014-10-26 || 2014-10-27 || 2014-10-28
---------------------------------------------------------------------------
slot 1 2 3 4 || 1 2 3 4 || 1 2 3 4
---------------------------------------------------------------------------
Location
1 35 36 34 34 35 36 32 32 35 33 35 33
2 45 46 41 39 46 44 45 42 41 40 42 41
將DataFrame.set_index
與DataFrame.unstack
DataFrame.set_index
使用,對於日期,請使用Series.dt.date
:
df['timeslot'] = pd.to_datetime(df['timeslot'])
df = df.set_index(['Location', df['timeslot'].dt.date, 'Slot'])['Weather'].unstack([1,2])
print (df)
timeslot 2014-10-26 2014-10-27 2014-10-28
Slot 1 2 3 4 1 2 3 4 1 2 3 4
Location
1 35 36 34 34 35 36 36 32 35 33 35 33
2 45 46 41 39 46 44 45 42 41 40 42 41
如果可能的話,請使用DataFrame.pivot_table
組合中的重復項(三重Location
, timeslot
日期和Slot
)進行匯總:
df = df.pivot_table(index='Location',
columns=[df['timeslot'].dt.date, 'Slot'],
values='Weather',
aggfunc='mean')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.