Pandas df.head() function
head() is one of the most commonly used functions in Pandas DataFrame and Series, used to quickly view the beginning of a dataset. It returns the first n rows, letting us understand the basic structure and content of the data without loading the entire dataset.
This function is used very frequently in data analysis, especially when working with large datasets; we usually first use head() to view the first few rows of the data, confirm that the structure matches expectations, and then proceed with further analysis and processing.
Basic syntax and parameters
head() is a member function of DataFrame and Series, called via the dot operator . . It requires no mandatory arguments but can accept an optional argument specifying the number of rows to return.
Syntax format
DataFrame.head(n=5)
Series.head(n=5)
Parameter Description
| Parameters | Type | Required | Description | Default value |
|---|---|---|---|---|
| n | int | Optional | Returns the first n rows. If n is greater than the total number of rows, all data is returned. | 5 |
Return value description
- Return value type: When the caller is a DataFrame, a DataFrame is returned; when the caller is a Series, a Series is returned.
- Returning the Line Count: Returns at most n rows; if there are fewer than n rows, all data is returned.
Example
Let us fully master it through a series of examples head() through a series of examples from simple to complex.
Example 1: Basic usage - viewing the first few rows of a DataFrame
First create a simple DataFrame, then use head() to view the first few rows of data.
Example
import
pandas
as
pd
Create a sample DataFrame containing student score data
data
=
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
,
'Frank'
,
'Grace'
,
'Henry'
,
'Iris'
,
'Jack'
]
,
'age'
:
[
18
,
19
,
17
,
18
,
20
,
19
,
18
,
17
,
19
,
18
]
,
'score'
:
[
85
,
92
,
78
,
90
,
88
,
95
,
82
,
76
,
89
,
91
]
,
'grade'
:
[
'A'
,
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
,
'C'
,
'B'
,
'A'
]
}
df
=
pd.
DataFrame
(
data
)
Return the first 5 rows by default
(
"First 5 rows by default:"
)
(
df.
head
(
)
)
Specify returning the first 3 rows
(
"nFirst 3 rows:"
)
(
df.
head
(
3
)
)
Return the first 7 rows
(
"nFirst 7 rows:"
)
(
df.
head
(
7
)
)
Running result:
Default first 5 lines:
name age score grade
0 Alice 18 85 A
1 Bob 19 92 A
2 Charlie 17 78 B
3 David 18 90 A
4 Eve 20 88 B
前 3 行:
name age score grade
0 Alice 18 85 A
1 Bob 19 92 A
2 Charlie 17 78 B
前 7 行:
name age score grade grade
0 Alice 18 85 A
1 Bob 19 92 A
2 Charlie 17 78 B
3 David 18 90 A
4 Eve 20 88 B
5 Frank 19 95 A
6 Grace 18 82 B
Code analysis:
- We created a DataFrame with 10 rows of student data.
df.head()With no arguments, it returns the first 5 rows by default, which is the most common usage.df.head(3)Returning the first 3 rows; you can adjust the number of rows as needed.- When the specified n is greater than the total number of rows, all data is returned without an error.
Example 2: Viewing the first few rows of a Series
head() applies not only to DataFrame but also to Series objects.
Example
import
pandas
as
pd
Create a Series containing a series of values
s
=
pd.
Series
(
[
10
,
20
,
30
,
40
,
50
,
60
,
70
,
80
,
90
,
100
]
)
View the first 3 elements of the Series
(
"First 3 elements:"
)
(
s.
head
(
3
)
)
Create a Series with an index
s2
=
pd.
Series
(
[
100
,
200
,
300
,
400
,
500
]
,
index
=
[
'a'
,
'b'
,
'c'
,
'd'
,
'e'
]
)
(
"nFirst 2 elements of the indexed Series:"
)
(
s2.
head
(
2
)
)
Running result:
First 3 elements:
0 10
1 20
2 30
dtype: int64
# The first 2 elements of a Series with an index:
a 100
b 200
dtype: int64
Code analysis:
- Series also supports the
head()method, returning the first n elements. - A Series with a custom index also works normally with
head(), and the original index is preserved.
Example 3: Combining with other functions
head() is often combined with other DataFrame functions for data exploration and analysis.
Example
import
pandas
as
pd
import
numpy
as
np
Create a larger DataFrame
np.
random
.
seed
(
42
)
Set a random seed to ensure reproducible results
df
=
pd.
DataFrame
(
{
'date'
: pd.
date_range
(
'2024-01-01'
,
periods
=
100
)
,
'value'
: np.
random
.
randn
(
100
)
.
round
(
2
)
,
'category'
: np.
random
.
choice
(
[
'A'
,
'B'
,
'C'
]
,
100
)
}
)
View data type information
(
"Data type information:"
)
(
df.
dtypes
)
(
)
View the first 10 rows of data
(
"First 10 rows of data:"
)
(
df.
head
(
10
)
)
Sort first, then view the first few rows
df_sorted
=
df.
sort_values
(
'value'
,
ascending
=
False
)
(
"nFirst 5 rows after sorting by value in descending order:"
)
(
df_sorted.
head
(
)
)
View statistical information for the first few rows
(
"nStatistical information for the first 5 rows:"
)
(
df.
head
(
)
.
describe
(
)
)
Running result:
Data type information:
date datetime64[ns]
value float64
category object
dtype: object
First 10 lines of data:
date value category
0 2024-01-01 0.34 A
1 2024-01-02 -0.23 B
2 2024-01-03 0.54 C
3 2024-01-04 -1.58 B
4 2024-01-05 -0.29 后几行
...
Top 5 rows sorted by value in descending order:
date value category
72 2024-03-13 2.87 C
55 2024-02-25 2.32 A
31 2024-02-01 2.21 B
64 2024-03-05 1.71 C
84 2024-03-25 1.55 A
Statistics of the first 5 lines:
age score
count 5.0 5.000
mean 18.0 87.200
std 1.0 5.403
min 17.0 78.000
50% 18.0 88.000
max 20.0 95.000
Code analysis:
head()It can be used together withsort_values()Used together: sort first, then view the first few rows.head()What is returned is still a DataFrame, so other DataFrame methods can be called on it.describe()You can perform statistical summaries on the datahead()returned by it.
Notes
head()does not modify the original DataFrame or Series; it returns a new object.- When n is less than or equal to 0, an empty DataFrame or empty Series is returned.
- For large datasets, first using
head()to view the structure is a good practice. head()The returned data preserves the original index values and is not renumbered.
Tip: In a Jupyter Notebook or JupyterLab environment, simply entering a DataFrame variable name and executing it displays, by default, the
head()result, which greatly facilitates data exploration.
Summary
head() is one of the most basic and practical data viewing functions in Pandas. It can quickly preview the beginning of a dataset, helping us understand key information such as data structure, column names, and data types.
In real data analysis work, we usually: first use head() to view the basic structure of the data, then use tail() to view the end of the data, and then use info() and describe() to understand the overall picture of the data. This "four-step data viewing routine" is a basic skill every data analyst should master.
Common Pandas functions