【问题标题】:Assigning datetime as index does not give DatetimeIndex将日期时间分配为索引不会给出 DatetimeIndex
【发布时间】:2019-05-09 17:13:09
【问题描述】:

我的 df 有一个名为“days”的字段。我需要从“天”和开始日期创建一个日期时间。可能很麻烦,但它有效:

for t in df.index:
    df.loc[t,'date']=datetime.date(startdate)+
    datetime.timedelta(days=df.loc[t,'days'])
df.index=df.date

当我尝试上采样时:

udf=df.resample('M',how='sum')

我明白了:

TypeError:仅适用于 DatetimeIndex、TimedeltaIndex 或 PeriodIndex,但得到了一个“索引”实例

如果我使用日期时间字段设置索引,为什么索引不会成为日期时间索引(或“DatetimeIndex”)? “日期”中的每个条目和索引都是日期时间,不是吗?

type(df.date[0])
<type 'datetime.date'>

type(df.index[0])
<type 'datetime.date'>

绕过它的方法是:

df.index=pd.to_datetime(df.index)

但我找不到任何解释为什么将现有日期时间分配给索引不起作用,但通过 pd.to_datetime(df.index) 将现有日期时间 (df.index) 转换为日期时间却可以。

【问题讨论】:

    标签: pandas datetimeindex


    【解决方案1】:

    Pandas 不会将 python 原生的 datetime 对象转换为 Timestamp 对象,从这些对象可以创建 datetimeindexs。阅读pandas.DatetimeIndex 文档会有所帮助。

    问题在于,为您的日期列添加datetime 对象不会创建pandas Timestamp 对象。 Pandas Timestampdatetime.datetime 的 Pandas 替代品

    Timestamp 是 python 的 Datetime 的 pandas 等价物,在大多数情况下可以互换。它是用于构成 DatetimeIndex 的条目的类型,以及 pandas 中其他面向时间序列的数据结构。

    查看pandas.Timestamp 文档

    df = pd.DataFrame(np.random.randn(10,4), columns = list('abcd')) # sample df
    df.index = pd.date_range(start='2018-1-1', end='2018-1-10') # use pandas to create a date range and set index
    df['date'] = pd.date_range(start='2018-1-1', end='2018-1-10') # also set as column values
    print(f"date column type: {type(df['date'][0])}\ndate index type: {type(df.index)}\n")
    
    df['date'] = df['date'].apply(lambda x: datetime.date(x)) # convert pandas timestamp to datetime.date
    print(f"type for datetime.date: {type(df['date'][0])}")
    
    df.set_index('date', inplace=True) # set datetime.date as index
    print(f"type for datetime.date as index: {type(df.index)}")
    

    出来:

    date column type: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
    date index type: <class 'pandas.core.indexes.datetimes.DatetimeIndex'>
    
    type for datetime.date: <class 'datetime.date'>
    type for datetime.date as index: <class 'pandas.core.indexes.base.Index'>
    

    查看第一个和第三个输出:

    &lt;class 'pandas._libs.tslibs.timestamps.Timestamp'&gt;&lt;class 'datetime.date'&gt;

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 2021-01-22
      相关资源
      最近更新 更多