简体   繁体   中英

Finding datetime object in pandas df column

I have the following code, where I want to determine if a datetime object exists in a data frame.

Here is the code:

df_grid['Date'] = pd.to_datetime(df_grid['Date'])
start_date = df_grid['Date'].iloc[0].date() 
end_date = df_grid['Date'].iloc[-1].date()
current_date = start_date

while current_date < end_date:
    current_date += datetime.timedelta(days=1)
    print(current_date)
    if current_date in df_grid['Date']: continue
    print('not in')

And here is what the dataframe column looks like:

Date
2021-11-01
2021-11-01
2021-11-01
2021-11-02
2021-11-02
2021-11-03
2021-11-03
...

Most of the dates do exist in the column; however, when I run the code, it indicates that none of the dates exist in the dataframe column. I've tried matching with and without.date() and get the same results.

Well, this is what I ended up doing to identify missing dates in the dateframe

    while current_date < end_date:
        missing = True
        for row in df_grid.index:
            if current_date == df_grid['Date'].iloc[row]:
                missing = False
                break
        if missing == True:
            [code to execute when date is missing]
        current_date += datetime.timedelta(days=1)

Seems a lot more inefficient than what I originally tried to do, but at least this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM