Baron Yugovich
Baron Yugovich

Reputation: 4307

Flatten nested pandas dataframe columns

After some aggregation, my dataframe looks something like this

  A     B
        B_min   B_max
0 11     3       6       
1 22     1       2
2 33     4       4

How do I make the columns be A, B_min and B_max, without any nesting? Simple and standard. I've tried reindex_axix() and unstack(), but nothing worked.

Upvotes: 2

Views: 1763

Answers (1)

jpp
jpp

Reputation: 164643

Here is one way, but I wish there was an in-built way to do this.

import pandas as pd

df = pd.DataFrame({'A': [11, 11, 22, 22, 33, 33],
                   'B': [3, 6, 1, 2, 4, 4]})

g = df.groupby('A', as_index=False).agg({'B': ['min', 'max']})

g.columns = ['_'.join(col).strip() if col[1] else col[0] for col in g.columns.values]

#     A  B_min  B_max
# 0  11      3      6
# 1  22      1      2
# 2  33      4      4

Upvotes: 2

Related Questions