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

How to reset the index of a Pandas dataframe starting from a user-defined value

I want to reset the index of a dataframe from a user-defined value, e.g. 42.

Let us consider a simple dataframe:

import pandas as pd
df=pd.DataFrame({'a':[1,2,3,4,5]})

This answer simply suggests shifting the dataframe’s indices:

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

df.index = df.index + 42

This returns:

    a
42  1
43  2
44  3
45  4
46  5

But is it possible to use pandas’ reset_index method to do the same?

The best solution that I found so far is to reset the index first and then shift the indices:

def reset_index_from_user_defined_value(df, starting_index = 42):
    df = df.reset_index(drop=True)
    df.index = df.index + starting_index
    return df

Is there a better way to achieve this?

>Solution :

this is one way to do it

set index using an array that starts with the user-defined start value

start=42
df.set_index( np.arange(start, start+len(df)))

    a
42  1
43  2
44  3
45  4
46  5
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