To get the first n rows from a pandas DataFrame, you can use the pandas head() function.

df.head() #Default will return the first 5 rows

When working with data and designing scripts to update data, sometimes it is useful to be able to do simple checks on our data to ensure everything is populating correctly.

The pandas head() function allows us to get the first n rows of our DataFrame. By default, n is 5, but you can change this to any valid integer.

Let’s say we have the following DataFrame.

df = pd.DataFrame({'Age': [43,23,71,49,52,37], 
      'Test_Score':[90,87,92,96,84,79]})

print(df)
# Output: 
   Age  Test_Score
0   43          90
1   23          87
2   71          92
3   49          96
4   52          84
5   37          79

We can get the first 5 rows by calling head().

print(df.head())

# Output: 
   Age  Test_Score
0   43          90
1   23          87
2   71          92
3   49          96
4   52          84

If we only want the first 2 rows, we pass “2” to head()

print(df.head(2))

# Output: 
   Age  Test_Score
0   43          90
1   23          87

If you want to get the last n rows from a pandas DataFrame, you can use the pandas tail() function.

Getting the First Row from a Pandas DataFrame

To get the first row from a pandas DataFrame, we can use the pandas head() function. All we need to do is pass “1” to head() to get the first row.

Let’s say we have the same DataFrame from above. Getting the first row is easy, as shown below in the following Python code.

print(df.head(1))

# Output: 
   Age  Test_Score
0   43          90

Hopefully this article has been useful for you to understand how to use the pandas head() function to get the first n rows from a pandas DataFrame.

Categorized in:

Python,

Last Update: March 20, 2024