Home > Software engineering >  How to get previous, current and next dates from a DataFrame
How to get previous, current and next dates from a DataFrame

Time:12-14

I'm new to python and I'm pretty stuck with this one!

I'm trying to extract a series of rows from a DataFrame based on a data value. More specifically I want to specify a date and also get any values that are one day previous and one day after.

Below is when approach I'm currently taking, but I can't figure a way to get the dates either side!

import pandas as pd

import numpy as np

rng = pd.date_range('2021-01-06', periods=9, freq='D')

sen_data = pd.DataFrame(
    {"Aq_date_Sen": rng},
)

which outputs a Dataframe of dates:

  Aq_date_Sen
0  2021-01-06
1  2021-01-07
2  2021-01-08
3  2021-01-09
4  2021-01-10
5  2021-01-11
6  2021-01-12
7  2021-01-13
8  2021-01-14

I then made a simple function that checks for a specified date and extracts it.

def Imagery_selector(check_date, dataframe):
    comparison_column = np.where(dataframe["Aq_date_Sen"] == check_date, True, False)
    dataframe["match"] = comparison_column
    new_sen = dataframe.query("match == True")
    return new_sen

What I'm trying to do is also extract any rows from the DataFrame that are also a day before and after the specified date.

So from the DataFrame outline above, I would like to output something like this, but also any duplicates that may occur:

  Aq_date_Sen
1  2021-01-07
2  2021-01-08
3  2021-01-09

I tried a few things like using the index int and adding and subtracting one to it, but that was the wrong approach!

Any help regarding this would be greatly appreciated!

CodePudding user response:

You can use the datetime.datetime and datetime.timedelta methods to create datetime objects and use .isin method to filter for matching dates.

from datetime import datetime, timedelta
check_date = datetime.strptime('2021-01-08','%Y-%m-%d')
relevant_dates = [check_date - timedelta(days=1), check_date, check_date   timedelta(days=1)]
out = sen_data[sen_data["Aq_date_Sen"].isin(relevant_dates)]

Output:

  Aq_date_Sen
1  2021-01-07
2  2021-01-08
3  2021-01-09
  • Related