【问题标题】:How to complete time series data with some missing dates with pandas如何使用 pandas 完成一些缺少日期的时间序列数据
【发布时间】:2016-08-03 06:05:03
【问题描述】:

我有这样的缺失日期的数据集。

date,value
2015-01-01,7392
2015-01-03,4928
2015-01-06,8672

这是我期望达到的。

date,value
2015-01-01,7392
2015-01-02,7392 # ffill 1st
2015-01-03,4928
2015-01-04,4928 # ffill 3rd
2015-01-05,4928 # ffill 3rd
2015-01-06,8672

我尝试了很多,我阅读了文档,但我找不到解决方案i。我猜想使用 df.resample('d',fill_method='ffill'),但我还没有到达这里。谁能帮我解决这个问题?

这就是我所做的。

>>> import pandas as pd
>>> df = pd.read_csv(text,sep="\t",index_col='date')
>>> df.index = df.index.to_datetime()
>>> index = pd.date_range(df.index[1],df.index.max())

这里我得到了从 2015-01-01 到 2015-01-06 的 DatetimeIndex。

>>> values = [ x for x in range(len(index)) ]
>>> df2 = pd.DataFrame(values,index=index)

接下来我要合并原始数据和DatetimeIndex。

>>> df + df2

             0   value
2015-01-01 NaN NaN
2015-01-02 NaN NaN
2015-01-03 NaN NaN
2015-01-04 NaN NaN
2015-01-05 NaN NaN
2015-01-06 NaN NaN

NaN?我很困惑。

>>> df3 = df + df2
>>> df3.info()

DatetimeIndex: 10 entries, 2015-01-01 to 2015-01-10
Data columns (total 2 columns):
value    0 non-null float64
dtypes: float64(1)

原来的值是int,后来转成float了。

我的错误是什么?

【问题讨论】:

  • 尝试 df.resample('d',fill_method='ffill') 时出了什么问题?
  • 我想将此作为编辑添加到我的答案中,但你打败了我。如果您的建议没有问题,那么我将删除我的答案。
  • 我猜 OP 已经尝试过了,但是出了点问题。我猜问题出在时间格式上(2015-01-02 被评估为 2 月 1 日而不是 1 月 2 日)。顺便说一句,请随意将其添加到您的答案中,这是 OP 自己的解决方案,不是我的。 :)

标签: python pandas time-series


【解决方案1】:

试试这个:

import numpy as np
df2 = pd.DataFrame(np.nan, index=index)
df.combine_first(df2).fillna(method='ffill')

combine_firstdf2 中的nan 值替换为原始df 中的值(如果它们存在)。然后,您可以使用fillna 填充剩余的nan 值。

【讨论】:

  • 非常感谢!您的评论有效,我做到了!
猜你喜欢
  • 2022-12-21
  • 2015-01-05
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
  • 1970-01-01
  • 2016-11-21
相关资源
最近更新 更多