熊猫:到特定日期还剩几天

时间:2019-07-20 10:42:58

标签: python pandas

我希望看到int和天数。但是,我看到了NaNtwo rowsfloat64。你能告诉我我在做什么错吗?

    >>> 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

1 个答案:

答案 0 :(得分:2)

问题是不同的索引值,如果减去大熊猫,请尝试对齐索引,并且由于不匹配而创建丢失的值。

解决方案是创建相同的索引值,例如由Series.reset_indexdrop=True组成:

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

或使用标量-通过Series.iat按位置选择第一个值:

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

更改为:

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

另一种想法是组合-用标量减去一个项Series-输出是一个项Series

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