Gere
Gere

Reputation: 12687

How to flatten MultiIndex by a method/expression in Pandas?

I'd like to flatten a hierarchical MultiIndex to a flat Index

Theoretically, assigning to df1.columns does the jobs, however I wonder whether there is a method call using a lambda for doing that?! It would make nicer pipe programming.

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.normal(size=(10,2)), columns=list("ab"))
df1 = (df
       .rolling(2)
       .agg(["min", "max"])
      )
df1.columns = df1.columns.map("{0[0]}_{0[1]}".format)
df1

Can I replace the columns in a method call with a lambda - hence inside the big parenthesis (but something nicer than a Python function with pipe though)?

Upvotes: 2

Views: 624

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

Updated solution with pandas 0.21.0+ using set_axis with inplace=False:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.normal(size=(10,2)), columns=list("ab"))
df1 = (df
       .rolling(2)
       .agg(["min", "max"])
      ).pipe(lambda x: x.set_axis([x.columns.map('_'.join)], axis=1, inplace=False))
df1

Output:

      a_min     a_max     b_min     b_max
0       NaN       NaN       NaN       NaN
1 -0.308058  0.234267 -1.470612  0.051591
2  0.234267  1.983296  0.051591  0.181318
3  1.729354  1.983296  0.181318  0.648528
4 -0.920250  1.729354  0.648528  0.982604
5 -1.588438 -0.920250  0.448492  0.982604
6 -1.588438 -0.388845 -1.751965  0.448492
7 -0.394825 -0.388845 -1.751965 -0.844420
8 -0.394825  0.657264 -0.844420 -0.000743
9  0.309141  0.657264 -0.067996 -0.000743

Upvotes: 0

piRSquared
piRSquared

Reputation: 294258

df.rolling(2).agg(["min", "max"]).T.apply(
    lambda x:
        x.append(pd.Series(dict(new='_'.join(x.name)))),
    1).set_index('new').rename_axis(None).T

enter image description here

Upvotes: 2

Related Questions