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)

print(df)

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

       Fruits  Price
0      Banana    2.0
1   Blueberry    1.5
2       Apple    3.0
3      Cherry    2.5
4       Mango    3.0
5   Pineapple    4.0
6  Watermelon    5.5
7      Papaya    3.5
8        Pear    1.5
9     Coconut    2.0

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:

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)

get_rows = df.head(4)

print(get_rows)

You’ll now get the first 4 rows:

      Fruits  Price
0     Banana    2.0
1  Blueberry    1.5
2      Apple    3.0
3     Cherry    2.5

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)

get_rows = df.head(-4)

print(get_rows)

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

      Fruits  Price
0     Banana    2.0
1  Blueberry    1.5
2      Apple    3.0
3     Cherry    2.5
4      Mango    3.0
5  Pineapple    4.0

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

Leave a Comment