Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Pivot - Swap 'columns' and 'values'

I have a working pivot based upon the following code:

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})

Based upon that code, I correctly receive the below output.

current_pivot

However, I would like to essentially swap the column with the metric to receive the below output. Is this possible?

desired_pivot

like image 504
PyNoob Avatar asked Jun 14 '18 15:06

PyNoob


1 Answers

I think all you need is a call to pandas.DataFrame.swaplevel after the initial pivot, followed by sorting the columns to group the top level (level=0):

# Assuming df holds the result of the pivot
df.swaplevel(0, 1, axis=1).sort_index(axis=1)
like image 135
Peter Leimbigler Avatar answered Oct 16 '22 15:10

Peter Leimbigler