DougKruger
DougKruger

Reputation: 4624

start pandas dataframe index from specified number

Rather than having a pandas dataframe index starting at 0, how to start from a specified number i.e. 120. My naive approach uses len(df.index) to get row count, then using that to generate a list of sequential numbers which is then attached to the dataframe and set to index. Any better way to just start index at a particular number instead of this naive approach?

Upvotes: 3

Views: 5354

Answers (3)

shivsn
shivsn

Reputation: 7838

this works and its easy :

 df.index +=120

Upvotes: 7

EdChum
EdChum

Reputation: 394099

You have to overwrite the IndexArray object directly, you can use np.arange or pd.RangeIndex to do this:

In [109]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df

Out[109]:
          a         b         c
0 -0.743707 -0.579372 -0.559999
1  0.902517 -0.595641  0.060594
2  1.285828  0.633603 -1.194275
3  0.944658 -0.133695  0.687517
4 -0.863778  0.631133  1.897758

In [114]:    
df.index = pd.RangeIndex(120,120 + len(df))
df

Out[114]:
            a         b         c
120 -0.743707 -0.579372 -0.559999
121  0.902517 -0.595641  0.060594
122  1.285828  0.633603 -1.194275
123  0.944658 -0.133695  0.687517
124 -0.863778  0.631133  1.897758

Upvotes: 2

Adam Hughes
Adam Hughes

Reputation: 16309

You can construct the dataframe with an index parameter. IE:

df = DataFrame(columns=['a','b','c'], index=[1,2,3], data)

Upvotes: 0

Related Questions