[英]pandas pivot dataframe with multiple groupby
我有一個熊貓數據框,其數據如下:
DF:
item day time data
0 item_0 2012-12-02 00:00:01 0.81
1 item_0 2012-12-02 00:00:02 0.07
2 item_0 2012-12-03 00:00:00 0.84
3 item_1 2012-12-02 00:00:01 0.47
項目+日期+時間的組合是唯一的
我正在嘗試轉換為:
item day time_0 time_1 time_2
0 item_0 2012-12-02 NaN 0.81 0.07
1 item_0 2012-12-03 0.84 NaN NaN
2 item_1 2012-12-02 NaN 0.47 ...
我努力了:
df_stage_1 = df.groupby(['item','day']).apply(lambda x: x['time'].tolist()).reset_index()
上面的代碼生成一個列表,但時間從00:00:00開始不對齊-我可以只檢查列表並添加和跟蹤索引(因此可以在這些索引處將Nan添加到值列表中)
df_stage_1 = pd.DataFrame(df_stage_1.tolist(), )
上面的代碼為我提供了一個(未對齊的)時間值的數據框,我可以將其對齊(請參見上文)並追加到在上述步驟中創建的數據框,但是我無法解決如何在正確的時間對齊的列中獲取該數據框的值
您可以使用pd.pivot_table
:
res = df.pivot_table(index=['item', 'day'], columns='time',
values='data', aggfunc='first').reset_index()
print(res)
time item day 00:00:00 00:00:01 00:00:02
0 item_0 2012-12-02 NaN 0.81 0.07
1 item_0 2012-12-03 0.84 NaN NaN
2 item_1 2012-12-02 NaN 0.47 NaN
另一種解決方案是set_index
, unstack
, reset_index
:
df.set_index(['item', 'day', 'time'])['data'].unstack().reset_index()
time item day 00:00:00 00:00:01 00:00:02
0 item_0 2012-12-02 NaN 0.81 0.07
1 item_0 2012-12-03 0.84 NaN NaN
2 item_1 2012-12-02 NaN 0.47 NaN
請記住, df.unstack
在大熊貓是指索引:它unstacks指數的最里面的級別,並將其擺動到列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.