How to rename columns with multiple levels after pandas pivot operation?
Here\'s some code to generate test data:
import pandas as pd
df = pd.DataFrame({
If you want to coalesce the multi-index into a single string index without caring about the index level order, you can simply map
a join
function over the columns, and assign the result list back:
df2.columns = list(map("_".join, df2.columns))
And for your question, you can loop through the columns where each element is a tuple, unpack the tuple and join them back in the order you want:
df2 = pd.pivot_table(df, index=["c0"], columns=["c01","c02"], values=["v1","v2"])
# Use the list comprehension to make a list of new column names and assign it back
# to the DataFrame columns attribute.
df2.columns = ["_".join((j,k,i)) for i,j,k in df2.columns]
df2.reset_index()