The Pandas DataFrame function last() used to select last periods of time series data based on a date offset. It can select the last few rows based on a date offset. It returns either Series or DataFrame that is a subset of the source object.
offset : It can be either string, DateOffset or dateutil.relativedelta that specifies the offset length of the data that will be selected. ie. '3D' will display all the rows having their index within the last 3 days.
1 import pandas as pd
2 import numpy as np
3
4 main = pd.date_range('2012-04-15', periods = 4, freq = '2D')
5 df = pd.DataFrame({'x': [1, 2, 3, 4]}, index = main)
6
7 res = df.last('3D')
8 print('The last rows of dataframe object :')
9 print(res)
In the above example, a dataframe object is created by using date_range() function. A dataframe object is created by specifying a dictionary object or an index. The last() function is called by specifying a string that specifies the offset value. The result is assigned to the variable that will be printed on console.
1 The last rows of dataframe object :
2 x
3 2012-04-19 3
4 2012-04-21 4
Example 2
1 import pandas as pd
2
3 ser1 = pd.date_range('2023-07-22', periods = 8, freq='12h')
4 df = pd.DataFrame({'x': [1, 2, 3, 4, 5, 6, 7, 8]}, index = ser1)
5
6 res = df.last('3D')
7 print('The last rows of dataframe object :')
8 print(res)
In the above example, a dataframe object is created by using date_range() function. A dataframe object is created by specifying a dictionary object or an index. The last() function is called by specifying a string that specifies the offset value. The result is assigned to the variable that will be print.
1 The last rows of dataframe object :
2 x
3 2023-07-23 00:00:00 3
4 2023-07-23 12:00:00 4
5 2023-07-24 00:00:00 5
6 2023-07-24 12:00:00 6
7 2023-07-25 00:00:00 7
8 2023-07-25 12:00:00 8
Note : FutureWarning: last is deprecated and will be removed in a future version. Please create a mask and filter using '.loc' instead.
Related options for your search