Pandas DataFrame asfreq() Method – Be on the Right Side of Change (original) (raw)


Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


FeFeel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd import numpy


The asfreq() method converts a time series to a specified frequency. To view a list of available frequencies, click here.

The syntax for this method is as follows:

DataFrame.asfreq(freq, method=None, how=None, normalize=False, fill_value=None)

Parameter Description
freq Click here to view the frequencies, or navigate to an IDE and run: print(pd.tseries.offsets.__all__)
method This parameter completes missing values in an indexed Series (non-NaN). The available options are: – backfill/bfill: last valid observation to the following valid observation. – pad/ffill: use the following valid observation to fill.
how The available options are start and end. The default is end.
normalize Determines whether to reset the output index to midnight.
fill_value This parameter is the fill value(s) to apply to missing values (not NaN values).

For this example, five (5) random integers generate and display on sequential (Daily Frequency) days and business (Business Day Frequency) days.

Code – Example 1

lst = np.random.randint(10,60, size=5) idx = pd.date_range('1/16/2022', periods=5, freq='D') series = pd.Series(lst, index= idx) df = pd.DataFrame({'Series': series}) print(df)

result = df.asfreq(freq='B') print(result)

Output

df (5 consecutive days)

| | Series | | | ---------- | -- | | 2022-01-16 | 13 | | 2022-01-17 | 15 | | 2022-01-18 | 19 | | 2022-01-19 | 42 | | 2022-01-20 | 26 |

result (5 business days – M-F)

| | Series | | | ---------- | -- | | 2022-01-17 | 15 | | 2022-01-18 | 19 | | 2022-01-19 | 42 | | 2022-01-20 | 26 |

January 16, 2022, does not display in the result table as it falls on Sunday.

Selecting 'B' as a frequency will ignore any date that does not fall between Monday-Friday.

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.