简体   繁体   中英

Pandas: Days left to a certain date

I expected to see an int with the number of days. However, I get to see NaN , two rows and float64 . Can you tell me what I am doing wrong here?

    >>> event_start_date = event_data['start_date'].loc[event_data['event_id'] == event_id]
    >>> last_order_date = event_orders['ds'].tail(1)
    >>> print(last_order_date)
    1493   2019-05-05 06:28:09.699094
    Name: ds, dtype: datetime64[ns]
    >>> print(event_start_date)
    0   2019-10-04 02:00:00
    Name: start_date, dtype: datetime64[ns]
    >>> days_to_event = (event_start_date - last_order_date).dt.days
    >>> print(days_to_event)
    0      NaN
    1061   NaN
    dtype: float64

Problem is different index values, if subtract pandas try align index and because not match are created missing values.

Solution is create same index values eg by Series.reset_index with drop=True :

days_to_event = (event_start_date.reset_index(drop=True) - 
                 last_order_date.reset_index(drop=True)).dt.days

Or working with scalars - select first value by position by Series.iat :

last_order_date = event_orders['ds'].tail(1)

change to:

last_order_date = event_orders['ds'].iat[0]
event_start_date = event_start_date.iat[0]

days_to_event = (event_start_date - last_order_date).days

Another idea is combination - subtract one item Series with scalar - output is one item Series :

last_order_date = event_orders['ds'].iat[0]
days_to_event = (event_start_date - last_order_date).dt.days

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