How to access a group of rows in a Pandas DataFrame?


To access a group of rows in a Pandas DataFrame, we can use the loc() method. For example, if we use df.loc[2:5], then it will select all the rows from 2 to 5.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
  • Print the input DataFrame, df.
  • Use df.loc[2:5] to select the rows from 2 to 5.
  • Print the DataFrame.

Example

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0, 7, 0, 5, 2],
      "y": [4, 7, 5, 1, 5, 1, 4, 7],
      "z": [9, 3, 5, 1, 5, 1, 9, 3]
   }
)


print "Input DataFrame is:\n", df
df = df.loc[2:5]
print "New DataFrame:\n", df

Output

Input DataFrame is:
   x  y  z
0  5  4  9
1  2  7  3
2  7  5  5
3  0  1  1
4  7  5  5
5  0  1  1
6  5  4  9
7  2  7 3

New DataFrame:
   x  y  z
2  7  5  5
3  0  1  1
4  7  5  5
5  0  1  1

Updated on: 14-Sep-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements