简体   繁体   中英

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, eg 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:

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM