[英]Pandas Dataframe Pivot-table: How to group by column values?
我有以下數據幀結構:
dimension month of year metric1 metric2
0 A 201809 xxxx xxxx
1 B 201809 xxx xxx
2 C 201808 xxx xxx
...
接下來我創建了一個數據透視表:
table = pd.pivot_table(df, values=['metric1', 'metric2'], index=['dimension'], columns=['ga:yearMonth'], aggfunc=np.sum)
這導致:
metric1 metric2
month of year 201807 201808 201809 201807 201808 201809
dimension
A x x x x x x
B x x x x x x
C x x x x x x
這非常接近我想要的,除了我想要按月份而不是指標對數字進行分組。 像這樣的東西:
month of year 201807 201808 201809
metric 1 2 1 2 1 2
dimension
A x x x x x x
B x x x x x x
C x x x x x x
環顧四周,我的理解是這將需要使用 MultiIndexing,盡管我一直無法找到可行的解決方案。
我只是為 metric1 和 metric2 設置了一些值。 但請參閱下面的代碼。
import pandas as pd
import numpy as np
df = pd.DataFrame([['A', '201809' ,234, 567],
['B', '201809' ,105, 640],
['C', '201808' ,250, 700],
['A', '201808' ,200, 267],
['B', '201809' ,57, 654],
['C', '201807' ,205, 620],
['A', '201807' ,234, 567],
['B', '201808' ,110, 640],
['C', '201808' ,275, 700],
['A', '201807' ,150, 267],
['B', '201807' ,57, 654],
['C', '201809' ,205, 620]
], columns=['dimension','month','metric1','metric2'])
df2 = pd.melt(df, id_vars=['dimension', 'month'], value_vars=['metric1', 'metric2'])
pd.pivot_table(df2, values=['value'], index=['dimension'], columns=['variable' , 'month'], aggfunc=np.sum)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.