pandas pivot table rename columns

后端 未结 1 940
小蘑菇
小蘑菇 2021-02-05 23:39

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({         


        
相关标签:
1条回答
  • 2021-02-05 23:49

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

    0 讨论(0)
提交回复
热议问题