Reputation: 337
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
Reputation: 18647
IIUC, use groupby.cumcount
and add 1:
df['count_of_Index1_Instances'] = df.groupby(level=['Index1']).cumcount().add(1)
Upvotes: 1