Pandas Pivot-交换“列”和“值”

PyN*_*oob 2 pivot python-3.x pandas

我有一个基于以下代码的工作枢纽:

pd.pivot_table(df,
index=["row_a","row_b"], 
columns=["col_a"],
values=["metric_a", "metric_b"],
aggfunc={"metric_a":np.max, "metric_b":np.sum})
Run Code Online (Sandbox Code Playgroud)

基于该代码,我正确地收到以下输出。

current_pivot

但是,我实际上希望将列与度量交换以接收以下输出。这可能吗?

wanted_pivot

Pet*_*ler 6

我认为您只需要pandas.DataFrame.swaplevel在初始数据透视表之后调用,然后对列进行排序以将顶层分组(级别= 0):

# Assuming df holds the result of the pivot
df.swaplevel(0, 1, axis=1).sort_index(axis=1)
Run Code Online (Sandbox Code Playgroud)