How to get the rows by using pandas series.first() method?



The pandas series.first() method is supposed to return initial periods based on the dates. By applying this method we can get the initial periods of the time series data based on a date offset.

It has a parameter called offset and also we can mention the length of the offset data to select the rows within the limit.

The first() method will return a now Series object with resultant rows and it will raise the TypeError if the index of the input series object doesn’t have the DatetimeIndex.

Example 1

In this following example, a series “s” is created by using the pandas DateTime index with the month name corresponding to the index.

# importing packages import pandas as pd # creating dates dates = pd.date_range('2021-08-15', periods=10, freq='m') #creating pandas Series with date index s = pd.Series(dates.strftime('%b'), index= dates) print (s) # get the rows by using first method result = s.first('1M') print('Result:') print(result)

Explanation

Here, we applied the first() method with offset “1M” to get the rows within one month.

Output

The output is as follows −

2021-08-31    Aug 2021-09-30    Sep 2021-10-31    Oct 2021-11-30    Nov 2021-12-31    Dec 2022-01-31    Jan 2022-02-28    Feb 2022-03-31    Mar 2022-04-30    Apr 2022-05-31    May Freq: M, dtype: object Result: 2021-08-31    Aug 2021-09-30    Sep Freq: M, dtype: object

We can see both the series objects, the first one is the original series object and the second one resultant series object. Here, we got the resultant series with 2 rows.

Example 2

In the same way, we have created a pandas object with pandas DateTime index. After that, we try to get rows that are having their index within 3 months.

# importing packages import pandas as pd # creating dates dates = pd.date_range('2021-01-20', periods=10, freq='2W') #creating pandas Series with date index s = pd.Series(dates.strftime('%b'), index= dates) print (s) # get the rows by using first method result = s.first('3M') print('Result:') print(result)

Output

The output is as follows −

2021-01-24    Jan 2021-02-07    Feb 2021-02-21    Feb 2021-03-07    Mar 2021-03-21    Mar 2021-04-04    Apr 2021-04-18    Apr 2021-05-02    May 2021-05-16    May 2021-05-30    May Freq: 2W-SUN, dtype: object Result: 2021-01-24    Jan 2021-02-07    Feb 2021-02-21    Feb 2021-03-07    Mar 2021-03-21    Mar Freq: 2W-SUN, dtype: object

The first method has successfully returned the new series object with 5 rows of data. And all these 5 rows have the index within the first 3 months.

Updated on: 2022-03-07T07:56:40+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements