Alex
Alex

Reputation: 632

Pandas: Change repeated index to hierarchical index

See the example below.

Given a dataframe whose index has values repeated, how can I get a new dataframe with a hierarchical index whose first level is the original index and whose second level is 0, 1, 2, ..., n?

Example:

>>> df
   0  1
a  2  4
a  4  6
b  7  8
b  2  4
c  3  7
>>> df2 = df.some_operation()
>>> df2
      0  1
a  0  2  4
   1  4  6
b  0  7  8
   1  2  4
c  0  3  7

Upvotes: 3

Views: 645

Answers (2)

U13-Forward
U13-Forward

Reputation: 71580

Can do the fake way (totally not recommended, don't use this):

>>> df.index=[v if i%2 else '' for i,v in enumerate(df.index)]
>>> df.insert(0,'',([0,1]*3)[:-1])
>>> df
      0  1
   0  2  4
a  1  4  6
   0  7  8
b  1  2  4
   0  3  7
>>> 

Change index names and create a column which the column name is '' (empty string).

Upvotes: 0

BENY
BENY

Reputation: 323306

You can using cumcount

df.assign(level2=df.groupby(level=0).cumcount()).set_index('level2',append=True)
Out[366]: 
          0  1
  level2      
a 0       2  4
  1       4  6
b 0       7  8
  1       2  4
c 0       3  7

Upvotes: 1

Related Questions