Pandas df.tail() Function
tail() It is an important function in Pandas DataFrame and Series, used to view the end portion of a dataset. It returns the last n rows, letting us quickly understand the end of the data and the latest records without traversing the entire dataset.
In time-series data analysis,tail() it is especially useful because we usually care about the latest data, such as recent stock prices, sales, or sensor readings. This function and head() complement each other, together forming the basic tools for data exploration.
Basic syntax and parameters
tail() is a member function of DataFrame and Series, called via the dot operator . to call. It is head() used exactly the same way, only looking in the opposite direction.
Syntax format
DataFrame.tail(n=5)
Series.tail(n=5)
Parameter Description
| Parameters | Type | Required | Description | Default value |
|---|---|---|---|---|
| n | int | Optional | Returns the last 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.
- Index preservation: The returned data retains the index values of the original DataFrame.
Example
Let us fully master the following through examples tail() through a series of examples from simple to complex.
Example 1: Basic Usage - Viewing the Last Rows of a DataFrame
Create a DataFrame and use tail() to view the end of the data.
Example
import
pandas
as
pd
Create a sample DataFrame
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 last 5 rows by default
(
"Last 5 rows by default:"
)
(
df.
tail
(
)
)
Specify returning the last 3 rows
(
"nLast 3 rows:"
)
(
df.
tail
(
3
)
)
Return the last 7 rows
(
"nLast 7 rows:"
)
(
df.
tail
(
7
)
)
Running result:
Default last 5 lines:
name age score grade
5 Frank 19 95 A
6 Grace 18 82 B
7 Henry 17 76 C
8 Iris 19 89 B
9 Jack 18 91 A
The last 3 lines:
name age score grade
7 Henry 17 76 C
8 Iris 19 89 B
9 Jack 18 91 A
The last 7 lines:
name age score grade
3 David 18 90 A
4 Eve 20 88 B
5 Frank 19 95 A
6 Grace 18 82 B
7 Henry 17 76 C
8 Iris 19 89 B
9 Jack 18 91 A
Code analysis:
- The DataFrame has 10 rows, indexed from 0 to 9.
df.tail()It returns the last 5 rows with indices 5 to 9.df.tail(3)Only the last 3 rows are returned, with indices 7, 8, 9.- Note that the index values retain the original DataFrame index and are not renumbered from 0.
Example 2: Viewing the Last Rows of a Series
tail() The same applies to Series objects.
Example
import
pandas
as
pd
Create a Series
s
=
pd.
Series
(
[
10
,
20
,
30
,
40
,
50
,
60
,
70
,
80
,
90
,
100
]
)
View the last 3 elements
(
"Last 3 elements:"
)
(
s.
tail
(
3
)
)
Create a Series with an index
s2
=
pd.
Series
(
[
100
,
200
,
300
,
400
,
500
]
,
index
=
[
'a'
,
'b'
,
'c'
,
'd'
,
'e'
]
)
(
"nLast 2 elements of the indexed Series:"
)
(
s2.
tail
(
2
)
)
Running result:
The last 3 elements:
7 80
8 90
9 100
dtype: int64
The last 2 elements of a Series with index:
d 500
e 600
dtype: int64
Code analysis:
- A Series'
tail()method returns the last n elements, preserving the original index. - The same applies to a Series with a custom index, returning the corresponding end elements.
Example 3: Application in Time-Series Data
When working with time-series data,tail() it is especially useful for quickly viewing the latest data records.
Example
import
pandas
as
pd
import
numpy
as
np
Create a time-series DataFrame simulating stock data
np.
random
.
seed
(
42
)
dates
=
pd.
date_range
(
'2024-01-01'
,
periods
=
30
,
freq
=
'D'
)
prices
=
100
- np.
cumsum
(
np.
random
.
randn
(
30
)
)
Simulate stock price trends
stock_df
=
pd.
DataFrame
(
{
'date'
: dates
,
'price'
: prices.
round
(
2
)
,
'volume'
: np.
random
.
randint
(
1000
,
10000
,
30
)
}
)
(
"Comparison of the first and last rows of the full data:"
)
(
"nFirst 5 rows:"
)
(
stock_df.
head
(
)
)
(
"nLast 5 rows:"
)
(
stock_df.
tail
(
)
)
Use tail to view the most recent days' data
latest_data
=
stock_df.
tail
(
7
)
(
"nData from the last 7 days:"
)
(
latest_data
)
Further analysis can be performed on the tail result
(
"nAverage price over the last 7 days:"
,
latest_data
[
'price'
]
.
mean
(
)
)
(
"Total volume over the last 7 days:"
,
latest_data
[
'volume'
]
.
sum
(
)
)
Running result:
Comparison of the first few and last few lines of the complete data:
前 5 行:
date price volume
0 2024-01-01 100.34 5234
1 2024-01-02 99.87 3421
2 2024-01-03 100.21 6789
3 2024-01-04 98.45 4321
4 2024-聚合-05 99.12 5654
The last 5 lines:
date price volume
25 2024-01-26 102.45 4321
26 2024-01-27 103.12 5678
27 2024-01-28 101.89 6543
28 2024-01-29 104.23 3211
29 2024-01-30 103.87 4532
Data for the last 7 days:
date price volume
23 2024-01-24 101.56 4321
24 2024-01-25 102.01 5432
25 2024-01-26 45 4321
26 2024-01-27 103.12 5678
27 2024-01-28 101.89 6543
28 2024-01-29 104.23 3211
29 2024-01-30 103.87 4532
最近 7 天的平均价格: 102.79
最近 7 天的总成交量: 34938
Code analysis:
- A DataFrame containing 30 days of stock price data was created.
tail() Quickly locate the latest data records.
- locks
tail() The returned data can be passed to other functions for computation and analysis.
- This pattern is very practical in real-time data analysis scenarios.
Notes
tail() 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,
tail() it is more efficient than loading all the data because it does not need to read the entire file.
tail() The difference between head() They are often used together to fully understand both ends of the data.
Tip: In the exploratory stage of data analysis, it is recommended to use both head() and tail(), so you can quickly determine whether the data is sorted as expected and whether it is complete.
Summary
tail() It is a Pandas function for viewing the end portion of data, and head() complements it. It is especially useful in time-series analysis, real-time data monitoring, log analysis, and other scenarios.
Mastering the head() and tail() these two functions, you can quickly understand the beginning and end of a dataset, which is an important first step in data exploration. Combined with info() and describe() and other functions, we can fully grasp the characteristics and distribution of the data.
Common Pandas functions