+

Python | Pandas Series.last ()

Series.last() Pandas Series.last() — it is a convenient method for substituting the final periods of time series data based on a date offset.

Syntax: Series.last (offset)

Parameter:
offset: string, DateOffset, dateutil.relativedelta

Returns: subset: same type as caller

Example # 1: Use Series.last () to return records from the last 5 days in a given series object.

Output:

We will now use Series.last () to return records from the last 5 days in this series object.

# import pandas as pd

import pandas as pd

 
# Create a series

sr = pd.Series ([ `New York` `Chicago` , ` Toronto` , `Lisbon` , ` Rio` , `Paris` ])

 
# Create index

index_ = pd.date_range ( `2010-10-09` , periods = 6 , freq = `2D` )

 
# set index

sr.index = index_

  
# Print series

print (sr)

# return posts from the last 5 days

result = sr.last ( `5D` )

 
# Print result

print (result)

Output:

As we can see in the output, Series.last () returned records from the last 5 days in this object of the series. Note that the function did not return the last 5 records, but the last 5 days.

Example # 2: Use Series.last () to return records for the last 4 months in this object of the series.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ 11 , 21 , 8 , 18 , 65 , 84 , 32 , 10 , 5 , 24 , 32 ])

 
# Create index

index_ = pd.date_range ( `2010-10-09` periods = 11 , freq = `M` )

 
# set index

sr. index = index_

 
# Print series

print (sr)

Output:

Now we will use Series.last () to return records from the last 4 months in this series object.

 

# return posts from the last 4 months

result = sr.last ( `4M` )

  
# Print result

print (result)

Output:

As we can see from the output, Series.last () returned records for the last 4 months in this series object.

Get Solution for free from DataCamp guru