Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas DataFrame RangeIndex

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

like image 404
MaxRussell Avatar asked Jun 09 '17 08:06

MaxRussell


People also ask

What does .index do in pandas?

The index property returns the index information of the DataFrame. The index information contains the labels of the rows. If the rows has NOT named indexes, the index property returns a RangeIndex object with the start, stop, and step values.


1 Answers

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
like image 165
jezrael Avatar answered Oct 10 '22 05:10

jezrael