gpt4 book ai didi

python - 将 pandas 时间序列从 object dtype 重新索引为 datetime dtype

转载 作者:IT老高 更新时间:2023-10-28 22:08:14 28 4
gpt4 key购买 nike

我有一个不被识别为 DatetimeIndex 的时间序列,尽管它被具有有效日期的标准 YYYY-MM-DD 字符串索引。将它们强制为有效的 DatetimeIndex 似乎不够优雅,让我觉得我做错了什么。

我读入(其他人的惰性格式)包含无效日期时间值的数据并删除了这些无效观察结果。

In [1]: df = pd.read_csv('data.csv',index_col=0)
In [2]: print df['2008-02-27':'2008-03-02']
Out[2]:
count
2008-02-27 20
2008-02-28 0
2008-02-29 27
2008-02-30 0
2008-02-31 0
2008-03-01 0
2008-03-02 17

In [3]: def clean_timestamps(df):
# remove invalid dates like '2008-02-30' and '2009-04-31'
to_drop = list()
for d in df.index:
try:
datetime.date(int(d[0:4]),int(d[5:7]),int(d[8:10]))
except ValueError:
to_drop.append(d)
df2 = df.drop(to_drop,axis=0)
return df2

In [4]: df2 = clean_timestamps(df)
In [5] :print df2['2008-02-27':'2008-03-02']
Out[5]:
count
2008-02-27 20
2008-02-28 0
2008-02-29 27
2008-03-01 0
2008-03-02 17

这个新索引仍然只被识别为“对象”dtype,而不是日期时间索引。

In [6]: df2.index
Out[6]: Index([2008-01-01, 2008-01-02, 2008-01-03, ..., 2012-11-27, 2012-11-28,
2012-11-29], dtype=object)

重新索引会产生 NaN,因为它们是不同的 dtype。

In [7]: i = pd.date_range(start=min(df2.index),end=max(df2.index))
In [8]: df3 = df2.reindex(index=i,columns=['count'])
In [9]: df3['2008-02-27':'2008-03-02']
Out[9]:
count
2008-02-27 NaN
2008-02-28 NaN
2008-02-29 NaN
2008-03-01 NaN
2008-03-02 NaN

我用适当的索引创建一个新的数据框,将数据放到字典中,然后根据字典值填充新的数据框(跳过缺失值)。

In [10]: df3 = pd.DataFrame(columns=['count'],index=i)
In [11]: values = dict(df2['count'])
In [12]: for d in i:
try:
df3.set_value(index=d,col='count',value=values[d.isoformat()[0:10]])
except KeyError:
pass
In [13]: print df3['2008-02-27':'2008-03-02']
Out[13]:

count
2008-02-27 20
2008-02-28 0
2008-02-29 27
2008-03-01 0
2008-03-02 17

In [14]: df3.index
Out[14];
<class 'pandas.tseries.index.DatetimeIndex'>
[2008-01-01 00:00:00, ..., 2012-11-29 00:00:00]
Length: 1795, Freq: D, Timezone: None

根据查找以字符串为键的字典来设置值的最后一部分似乎特别笨拙,让我觉得我错过了一些重要的事情。

最佳答案

您可以使用 pd.to_datetime:

In [1]: import pandas as pd

In [2]: pd.to_datetime('2008-02-27')
Out[2]: datetime.datetime(2008, 2, 27, 0, 0)

这允许您通过将索引(或类似的列)应用于系列来“清理”索引(或类似的列):

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

df['date_col'] = df['date_col'].apply(pd.to_datetime)

关于python - 将 pandas 时间序列从 object dtype 重新索引为 datetime dtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13654699/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com