-2

Given a dataframe, how do I get every nth row within some range of rows?

for instance, suppose I have this dataframe:

i  |  A   |  B  |
---|------|-----|
0  | 0.2  | 33  |
1  | 0.3  | 77  |
2  | 10   | 77  |
3  | 30   | 33  |
4  | 27   | 20  |
5  | 99   | 8   |
6  | 100  | 33  |
7  | 27   | 33  |
8  | 27   | 77  |

how could I extract every other row between index 2 and 7?

Warlax56
  • 1,170
  • 5
  • 30
  • https://pandas.pydata.org/docs/user_guide/indexing.html – wwii Mar 22 '21 at 18:54
  • I'm not sure why this is so downvoted? There is a solution for every nth row (https://stackoverflow.com/questions/25055712/pandas-every-nth-row) but not within a range. Figured I would contribute to the community? If you have suggestions let me know instead of downvoting, this is a legitimate question about a very common use case. – Warlax56 Mar 25 '21 at 16:33

1 Answers1

0

First, we can create a test dataframe:

from pandas import util
tdf= util.testing.makeDataFrame()

then, we can index it in the following way:

tdf[start_index:end_index:step_size]

so, getting every other row from index 10 to 20 would look like this:

tdf[10:20:2]
Warlax56
  • 1,170
  • 5
  • 30