0

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!

1
  • Is this what you mean.. df.groupby(level=['Index1']).cumcount().add(1)? Commented Mar 14, 2019 at 17:09

1 Answer 1

1

IIUC, use groupby.cumcount and add 1:

df['count_of_Index1_Instances'] = df.groupby(level=['Index1']).cumcount().add(1)
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.