Pandas DataFrame asof() Method


Preparation

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

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

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

DataFrame asof()

The asof() method retrieves and returns the last row(s) of a DataFrame/Series (non-NaN values) based on the date(s) entered in the where parameter.

The syntax for this method is as follows:

DataFrame.asof(where, subset=None)
ParameterDescription
whereThis parameter is a single date or array of dates before the last row(s) return.
subsetDataFrame columns to check for NaN values.

For this example, we pass a single date. One date matches, and the appropriate value returns.

Code – Example 1

nums = np.random.randint(1,50, size=7)
idx = pd.date_range('1/24/2022', periods=7, freq='D')
series = pd.Series(nums, index=idx)
print(series)

result = series.asof('1/27/2022')
print(result)
  • Line [1] generates seven (7) random integers between the specified range and saves them to nums.
  • Line [2] does the following:
    • An index creates based on the start date for five (5) days.
    • The frequency changes to ‘D’ (Daily Frequency).
    • The output saves to idx.
  • Line [3] creates a series based on the nums and idx variables. The output saves to series.
  • Line [4] outputs the series to the terminal.
  • Line [5] retrieves a single value associated with the specified date and saves it to result.
  • Line [6] outputs the result to the terminal.

Output

df (7 consecutive days)

 Series
2022-01-24     10
2022-01-25     34
2022-01-26    31
2022-01-2725
2022-01-28    35
2022-01-2941
2022-01-30    49

result (2022-01-27)

Freq: D, dtype: int32
25

A CSV file containing five (5) rows reads in and saves to a DataFrame.

Code – Example 2

df = pd.read_csv('data.csv', parse_dates=['date'])
df.set_index('date', inplace=True)
print(df)

result = df['price'].asof(pd.DatetimeIndex(['2022-02-27 09:03:30', '2022-02-27 09:04:30']))
print(result)
  • Line [1] creates a DataFrame from the CSV file and parses the date field using parse_dates(). This output saves to df.
  • Line [2] sets the index for the DataFrame on the date field and inplace=True.
  • Line [3] outputs the DataFrame to the terminal.
  • Line [4] retrieves the price(s) based on the specified date range. The output saves to result.
  • Line [5] outputs the result to the terminal.

Output

df

 price
date     
2022-02-27 09:01:00  8.12
2022-02-27 09:02:00  8.33
2022-02-27 09:03:008.36
2022-02-27 09:04:008.29
2022-02-27 09:05:008.13

result

2022-02-27 09:03:30   8.36
2022-02-27 09:04:30   8.29
Name: price, dtype: float64

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.