12

I have created a Pandas DataFrame. I need to create a RangeIndex for the DataFrame that corresponds to the frame - RangeIndex(start=0, stop=x, step=y) - where x and y relate to my DataFrame.

I've not seen an example of how to do this - is there a method or syntax specific to this?

thanks

sophros
  • 14,672
  • 11
  • 46
  • 75
MaxRussell
  • 518
  • 1
  • 11
  • 25

1 Answers1

12

It seems you need RangeIndex constructor:

df = pd.DataFrame({'A' : range(1, 21)})
print (df)
     A
0    1
1    2
2    3
3    4
4    5
5    6
6    7
7    8
8    9
9   10
10  11
11  12
12  13
13  14
14  15
15  16
16  17
17  18
18  19
19  20


print (df.index)
RangeIndex(start=0, stop=20, step=1)

df.index = pd.RangeIndex(start=0, stop=99, step=5)
print (df)
     A
0    1
5    2
10   3
15   4
20   5
25   6
30   7
35   8
40   9
45  10
50  11
55  12
60  13
65  14
70  15
75  16
80  17
85  18
90  19
95  20

print (df.index)
RangeIndex(start=0, stop=99, step=5)

More dynamic solution:

step = 10
df.index = pd.RangeIndex(start=0, stop=len(df.index) * step - 1, step=step)
print (df)
      A
0     1
10    2
20    3
30    4
40    5
50    6
60    7
70    8
80    9
90   10
100  11
110  12
120  13
130  14
140  15
150  16
160  17
170  18
180  19
190  20

print (df.index)
RangeIndex(start=0, stop=199, step=10)

EDIT:

As @ZakS pointed in comments better is use only DataFrame constructor:

df = pd.DataFrame({'A' : range(1, 21)}, index=pd.RangeIndex(start=0, stop=99, step=5))
print (df)
0    1
5    2
10   3
15   4
20   5
25   6
30   7
35   8
40   9
45  10
50  11
55  12
60  13
65  14
70  15
75  16
80  17
85  18
90  19
95  20
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 1
    would this be the same as just creating an array, and passing it in to the dataframe as the index? – ZakS May 30 '18 at 08:17
  • 1
    I might just add that per the documentation, leaving it out will create it with steps of 1 automatically – ZakS May 30 '18 at 08:26
  • RangeIndex(start=0, stop=240, step=1) \n months object \n Event Probability object Probability % float64 dtype: object can you please tell me how to limit only the months column ? – Sumathi J Apr 23 '22 at 12:20