Lisa
Lisa

Reputation: 337

Add range of mulitlevel index in Python

I would like to add a column containing the range of the first level of a multi-level index in Python. For example:

| Index1| Index2| count_of_Index1_Instances |  
---------------------------------------------
|   1   |  20   |           1              |
|       |  40   |           2              |
|       |  10   |           3              |
|   2   |  20   |           1              |

I know thedf.groupby(level=['Index1']).size() command, but this is not what I am looking for. The result in the last column should be a range from 1 to the size of Index-Group1.
Some piece of code would be great!
Thank you!

Upvotes: 0

Views: 20

Answers (1)

Chris Adams
Chris Adams

Reputation: 18647

IIUC, use groupby.cumcount and add 1:

df['count_of_Index1_Instances'] = df.groupby(level=['Index1']).cumcount().add(1)

Upvotes: 1

Related Questions