Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting index counter on a data frame

I have the following data frame:

import pandas as pd

data = {
    "id_1": [1, 1, 1, 2, 2, 2],
    "id_2": [1, 1, 1, 2, 2, 2],
    "foo": [0.1, 0.1, 0.1, 0.2, 0.2, 0.2],
}
df = pd.DataFrame(data)
df = df.set_index(["id_1", "id_2"])

which looks like this:

           foo
id_1 id_2
1    1     0.1
     1     0.1
     1     0.1
2    2     0.2
     2     0.2
     2     0.2

I want to have another column (index) that starts from 1 and goes up to the length of the index group, 3. The output should look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

           foo index
id_1 id_2
1    1     0.1 1
     1     0.1 2
     1     0.1 3
2    2     0.2 1
     2     0.2 2
     2     0.2 3

How do I go about this, please?

>Solution :

One approach could be as follows:

  • Use df.groupby with level=0, and apply Groupby.cumcount to get consecutive numbers for each item in each group.
  • Since the numbering will start at 0, we use Series.add to add 1 to the result.
df['index'] = df.groupby(level=0).cumcount().add(1)

df

           foo  index
id_1 id_2            
1    1     0.1      1
     1     0.1      2
     1     0.1      3
2    2     0.2      1
     2     0.2      2
     2     0.2      3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading