Home > Software design >  Pandas formated Datetime Column - Filter results by a specific Day of Week
Pandas formated Datetime Column - Filter results by a specific Day of Week

Time:09-21

I only want results where day equals Thursday. I'm able to filter the open sites and ff which is first come first server but not sure how to filter by a specific day from my formated date. Thank you

def main():
    result = []
    print('Checking for available  campsites....')

    for unit_id in list(range(5095, 5096))   [5117]   [5056]   [5078]   [5111]   [5113]   [5115]   [5119]:
        resp = requests.get(
            f"https://calirdr.usedirect.com/rdr/rdr/fd/"
            f"availability/getbyunit/{unit_id}/startdate/{day_today}/nights/60/true?").json()
        result.extend(resp)

    df = pd.DataFrame(result)
    df.rename(columns={'UnitId': 'Site', 'StartTime': 'Date', 'IsFree': 'Open', 'IsWalkin': 'FF'}, inplace=True)
    filter_by = ['Site', 'Date', 'Open', 'FF']
    df = df.filter(items=filter_by)
    df['Date'] = df['Date'].apply(lambda d: datetime.fromisoformat(d).strftime("%m-%d-%y %A "))
    # I only want results where day equals Thursday
    df = df[df['Open']]
    df = df[~df['FF']]
    print(df)

PRINTED RESULT

    Site                 Date  Open     FF
    5095   09-23-21 Thursday   True  False
    5095    10-19-21 Tuesday   True  False
    5095  10-20-21 Wednesday   True  False
    5095   10-21-21 Thursday   True  False

CodePudding user response:

You can use pandas.Series.day_name(). If you keep the Date column as datetime64 instead of converting it to string:

# Example data based on your final DataFrame
df = pd.DataFrame({'Site': [5095, 5095, 5095, 5095],
                   'Date': ['2021-09-23', '2021-10-19', '2021-10-20', '2021-10-21'],
                   'Open': [True, True, True, True],
                     'FF': [False, False, False, False]})

print(df)

   Site       Date  Open     FF
0  5095 2021-09-23  True  False
1  5095 2021-10-19  True  False
2  5095 2021-10-20  True  False
3  5095 2021-10-21  True  False

df[df['Date'].dt.day_name() == 'Thursday']

   Site       Date  Open     FF
0  5095 2021-09-23  True  False
3  5095 2021-10-21  True  False

CodePudding user response:

Or why not just:

df[df['Date'].dt.dayofweek == 4]
  • Related