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:
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?
CodePudding user response:
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