What is Pandas DataFrame.head() in Python?

Overview

Python has many modules, but pandas is one of the best at analyzing data. The DataFrame.head() function prints the first n number of rows from the top of DataFrame. It is very useful in data analysis to check dataset attributes.

Syntax


# function syntax
DataFrame.head(n)

Parameter

It takes the following value as an argument:

  • n: This is the numberinteger value of rows or observations to extract from the head of DataFrame.
If n < 0, it will return last n rows of DataFrame.

Return value

It returns segmented DataFrame as a series or DataFrame.

Code

#Import panda module
import pandas as panda
#Import NumPy module
import numpy as numpy
#Dataframe of students data
students = panda.DataFrame({
'Name': ['John', 'Rick', 'Alex', 'Ryan', 'Will', 'Alice'],
'Marks' : ['15', '19', '10', '13', '15', '17']})
#Print the first 4 rows from students dataframe
print(students.head(4))

Explanation

  • Lines 2 and 4: We import the panda and numpy modules.
  • Line 6: We add data in two columns of Name and Marks with respective data in it.
  • Line 10: We print the first four rows from the students using the DataFrame.head() function.

Free Resources