pandas pivot table重命名列

muo*_*uon 7 python pivot pivot-table data-mining pandas

如何在pandas pivot操作后重命名多个级别的列?

以下是生成测试数据的一些代码:

import pandas as pd
df = pd.DataFrame({
    'c0': ['A','A','B','C'],
    'c01': ['A','A1','B','C'],
    'c02': ['b','b','d','c'],
    'v1': [1, 3,4,5],
    'v2': [1, 3,4,5]})

print(df)
Run Code Online (Sandbox Code Playgroud)

给出一个测试数据帧:

   c0 c01 c02  v1  v2
0  A   A   b   1   1
1  A  A1   b   3   3
2  B   B   d   4   4
3  C   C   c   5   5
Run Code Online (Sandbox Code Playgroud)

应用枢轴

df2 = pd.pivot_table(df, index=["c0"], columns=["c01","c02"], values=["v1","v2"])
df2 = df2.reset_index()
Run Code Online (Sandbox Code Playgroud)

OUTPUT1

如何通过加入级别重命名列?格式 <c01 value>_<c02 value>_<v1>

例如,第一列应该是这样的 "A_b_v1"

加入级别的顺序对我来说并不重要.

Psi*_*dom 12

如果要将多索引合并为单个字符串索引而不关心索引级别顺序,则可以简单地对列进行map一个join函数,并将结果列表分配回来:

df2.columns = list(map("_".join, df2.columns))
Run Code Online (Sandbox Code Playgroud)

对于您的问题,您可以遍历每个元素都是元组的列,解压缩元组并按照您想要的顺序将它们连接起来:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 谢谢```['_'.join(str(s).strip()for s in col if s)for col in df2.columns]```作为一般解决方案,独立于级别数 (3认同)