python - 在多索引数据框中移动缺少日期的列

标签 python pandas time-series missing-data multi-index

我想移动多索引数据框中的列,以便计算具有滞后自变量的回归模型。由于我的时间序列缺少值,我只想将已知的前几天的值转移。 df 看起来像这样:

                cost
ID  day
1   31.01.2020  0
1   03.02.2020  0
1   04.02.2020  0.12
1   05.02.2020  0
1   06.02.2020  0
1   07.02.2020  0.08
1   10.02.2020  0
1   11.02.2020  0
1   12.02.2020  0.03
1   13.02.2020  0.1
1   14.02.2020  0

所需的输出如下:

                cost   cost_lag
ID  day
1   31.01.2020  0      NaN
1   03.02.2020  0      NaN
1   04.02.2020  0.12   0
1   05.02.2020  0      0.12
1   06.02.2020  0      0
1   07.02.2020  0.08   0
1   10.02.2020  0      NaN
1   11.02.2020  0      0
1   12.02.2020  0.03   0
1   13.02.2020  0.1    0.03
1   14.02.2020  0      0.1 

基于this answer to a similar question我尝试过以下方法:

df['cost_lag'] = df.groupby(['id'])['cost'].shift(1)[df.reset_index().day == df.reset_index().day.shift(1) + datetime.timedelta(days=1)]

但这会导致我不明白的错误消息:

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match

我还尝试按照建议的方法填补缺失的日期 here :

ams_spend_ranking_df = ams_spend_ranking_df.index.get_level_values(1).apply(lambda x: datetime.datetime(x, 1, 1))

再次导致错误消息,但我无法理解:

AttributeError: 'DatetimeIndex' object has no attribute 'apply'

长话短说:如果我没有前一天的数据,如何将成本列移动 1 天并添加 NaN?

最佳答案

您可以通过 DataFrameGroupBy.resample 添加所有缺失的日期时间与 Resampler.asfreq :

df1 = df.reset_index(level=0).groupby(['ID'])['cost'].resample('d').asfreq()
print (df1)
ID  day       
1   2020-01-31    0.00
    2020-02-01     NaN
    2020-02-02     NaN
    2020-02-03    0.00
    2020-02-04    0.12
    2020-02-05    0.00
    2020-02-06    0.00
    2020-02-07    0.08
    2020-02-08     NaN
    2020-02-09     NaN
    2020-02-10    0.00
    2020-02-11    0.00
    2020-02-12    0.03
    2020-02-13    0.10
    2020-02-14    0.00
Name: cost, dtype: float64

那么如果将您的解决方案与 DataFrameGroupBy.shift 一起使用它像需要一样工作:

df['cost_lag'] = df1.groupby('ID').shift(1)
print (df)
               cost  cost_lag
ID day                       
1  2020-01-31  0.00       NaN
   2020-02-03  0.00       NaN
   2020-02-04  0.12      0.00
   2020-02-05  0.00      0.12
   2020-02-06  0.00      0.00
   2020-02-07  0.08      0.00
   2020-02-10  0.00       NaN
   2020-02-11  0.00      0.00
   2020-02-12  0.03      0.00
   2020-02-13  0.10      0.03
   2020-02-14  0.00      0.10

关于python - 在多索引数据框中移动缺少日期的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61867052/

相关文章:

javascript - 我们可以在 PUBNUB 中重新发布消息吗

python - 类型错误 : bad operand type for unary ~: 'float' while groupby and apply a function

python - 使用 Pandas 将列复制到文件时遇到问题

Python - Pandas 使用字符串删除行

python - 没有线条和误差线的 Pandas 线图(来自带有剪切的 groupby)

python - pandas.concat : Cannot handle a non-unique multi-index! Pandas Python

Python - 在循环中使用预定义变量列表(psychopy)

PHP CURL 发送 POST 到 Django 应用程序问题

matlab - 如何对时间序列数据执行 K 均值聚类?

Matlab:计算时间序列模型的协方差矩阵的逆