How to get the first N rows in Pandas DataFrame

You can use df.head() to get the first N rows in Pandas DataFrame.

For example, if you need the first 4 rows, then use:

df.head(4)

Alternatively, you can specify a negative number within the brackets to get all the rows, excluding the last N rows.

For example, you can use the following syntax to get all the rows excluding the last 4 rows:

df.head(-4)

Complete example to get the first N rows in Pandas DataFrame

Step 1: Create a DataFrame

Let’s create a simple DataFrame with 10 rows:

import pandas as pd

data = {'Fruits': ['Banana','Blueberry','Apple','Cherry','Mango','Pineapple','Watermelon','Papaya','Pear','Coconut'],
        'Price': [2,1.5,3,2.5,3,4,5.5,3.5,1.5,2]
        }

df = pd.DataFrame(data, columns = ['Fruits', 'Price'])

print (df)

As you can see, there are 10 rows in the DataFrame:

How to get the first N rows in Pandas DataFrame

Step 2: Get the first N Rows in Pandas DataFrame

You can use the following syntax to get the first 4 rows in the DataFrame (depending on your needs, you may specify a different number of rows inside the brackets):

df.head(4)

Here is the complete code to get the first 4 rows for our example:

import pandas as pd

data = {'Fruits': ['Banana','Blueberry','Apple','Cherry','Mango','Pineapple','Watermelon','Papaya','Pear','Coconut'],
        'Price': [2,1.5,3,2.5,3,4,5.5,3.5,1.5,2]
        }

df = pd.DataFrame(data, columns = ['Fruits', 'Price'])

get_rows = df.head(4)

print (get_rows)

You’ll now get the first 4 rows:

First N rows in Pandas DataFrame

Step 3 (Optional): Get all the rows, excluding the last N rows

Let’s suppose that you’d like to get all the rows, excluding the last N rows.

For example, you can use the code below in order to get all the rows excluding the last 4 rows:

import pandas as pd

data = {'Fruits': ['Banana','Blueberry','Apple','Cherry','Mango','Pineapple','Watermelon','Papaya','Pear','Coconut'],
        'Price': [2,1.5,3,2.5,3,4,5.5,3.5,1.5,2]
        }

df = pd.DataFrame(data, columns = ['Fruits', 'Price'])

get_rows = df.head(-4)

print (get_rows)

You’ll now see all the rows excluding the last 4 rows:

How to get the first N rows in Pandas DataFrame

You can check the Pandas Documentation to learn more about df.head().