Tuesday, 5 September 2023

Pandas: Get the last n elements of the series

Using tail method, we can get the rows from the series end

 

Example

series.tail() : Return last 5 rows in the series.
series.tail(n) : Return last n rows in the series.

 

Find the below working application.

 

tail.py
import pandas as pd

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
series = pd.Series(primes)

print('Original Data : ')
print(series)

last_five_primes = series.tail()
last_three_primes = series.tail(3)

print('\nlast_five_primes')
print(last_five_primes)

print('\nlast_three_primes')
print(last_three_primes)

 

Output

Original Data : 
0      2
1      3
2      5
3      7
4     11
5     13
6     17
7     19
8     23
9     29
10    31
dtype: int64

last_five_primes
6     17
7     19
8     23
9     29
10    31
dtype: int64

last_three_primes
8     23
9     29
10    31
dtype: int64

‘tail()’ method is a preview on original dataset, if you update something on the result returned by tail() method, it updates the original data. You can confirm the same from below application.

 

tail.py

import pandas as pd

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
series = pd.Series(primes)

print('Original Data : ')
print(series)

last_five_primes = series.tail()
last_three_primes = series.tail(3)

print('\nlast_five_primes')
print(last_five_primes)

print('\nlast_three_primes')
print(last_three_primes)

Output

Original Data : 
0      2
1      3
2      5
3      7
4     11
5     13
6     17
7     19
8     23
9     29
10    31
dtype: int64

last_five_primes
6     17
7     19
8     23
9     29
10    31
dtype: int64

last_three_primes
8     23
9     29
10    31
dtype: int64

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment