Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas select n middle rows

Suppose I have a dataframe, df like this

col1 col2 col3
 1     2     34
 11    32    32
 21    62    34
 31    12    31
 13    82    35
 11    32    33
 41    32    33

and I want to select 3 rows after first 2 rows, that is I want to select these rows

 21    62    34
 31    12    31
 13    82    35

How can I do this?

like image 961
asdlfkjlkj Avatar asked Sep 23 '17 13:09

asdlfkjlkj


People also ask

How do I print last 10 rows in Python?

Method 1: Using tail() method Use pandas. DataFrame. tail(n) to get the last n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the end).

How can you get the first five records in a DataFrame?

You can use df. head() to get the first N rows in Pandas DataFrame. Alternatively, you can specify a negative number within the brackets to get all the rows, excluding the last N rows.

What does the pandas head () method do?

The head() method returns a specified number of rows, string from the top. The head() method returns the first 5 rows if a number is not specified. Note: The column names will also be returned, in addition to the specified rows.


2 Answers

Use slicing of rows with loc to do that like df.loc[2:5]

Output:

  col1  col2  col3
2    21    62    34
3    31    12    31
4    13    82    35
5    11    32    33

If you want to ignore the current index then use slicing with iloc which will get the rows between the range.

df.iloc[2:4]
  col1  col2  col3
2    21    62    34
3    31    12    31
like image 50
Bharath Avatar answered Sep 21 '22 07:09

Bharath


You can do df.iloc[2:4] or just df[2:4].

like image 38
Daniel Severo Avatar answered Sep 21 '22 07:09

Daniel Severo