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.
However, I would like to essentially swap the column with the metric to receive the below output. Is this possible?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With