Pandas PivotTable Rename Columns

How to rename columns with multiple levels after pandas pivot operation?

Here is the code for generating test data:

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)

provides a test file:

   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

rotation application

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

gives

output1

How to rename columns by joining levels? with format <c01 value>_<c02 value>_<v1>

for example, the first column should look like this: "A_b_v1"

The order of the levels is not very important for me.

+4
source share
1 answer

You can scroll the columns where each element is a tuple, unzip the tuple and attach 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()

enter image description here

+7
source

Source: https://habr.com/ru/post/1669075/


All Articles