Python Pandas - 将绝对周期转换为相对周期

标签 python pandas time-series dataframe

我有一个数据框,我想用它来计算相对于事件日期的滚动总和。每列的事件日期都不同,并以每列中有值的最新日期表示。

这是一个玩具示例:

rng = pd.date_range('1/1/2011', periods=8, freq='D')
df = pd.DataFrame({
            '1' : [56, 2, 3, 4, 5, None, None, None],
            '2' : [51, 2, 3, 4, 5, 6, None, None],
            '3' : [51, 2, 3, 4, 5, 6, 0, None]}, index = rng)

pd.rolling_sum(df,3)

它生成的数据框如下所示:

            1       2       3
2011-01-01  NaN     NaN     NaN
2011-01-02  NaN     NaN     NaN
2011-01-03  61      56      56
2011-01-04  9       9       9
2011-01-05  12      12      12
2011-01-06  NaN     15      15
2011-01-07  NaN     NaN     11
2011-01-08  NaN     NaN     NaN

我现在想要对齐数据帧最后一行上的最后一个事件日期,并将索引设置为 0,前面的行索引为 -1、-2、-3 等。这些周期不再是绝对的,而是相对于事件日期的。

所需的数据框如下所示:

    1   2   3
-7.00   NaN NaN NaN
-6.00   NaN NaN NaN
-5.00   NaN NaN NaN
-4.00   NaN NaN 56
-3.00   NaN 56  9
-2.00   61  9   12
-1.00   9   12  15
0.00    12  15  11

感谢您的指导。

最佳答案

我没有看到任何简单的方法可以做到这一点。以下内容可以工作,但有点困惑。

In [37]: def f(x):
   ....:     y = x.dropna()
   ....:     return Series(y.values,x.index[len(x)-len(y):])
   ....: 

In [40]: roller = pd.rolling_sum(df,3).reset_index(drop=True)

In [41]: roller
Out[41]: 
    1   2   3
0 NaN NaN NaN
1 NaN NaN NaN
2  61  56  56
3   9   9   9
4  12  12  12
5 NaN  15  15
6 NaN NaN  11
7 NaN NaN NaN

[8 rows x 3 columns]

In [43]: roller.apply(f).reindex_like(roller)
Out[43]: 
    1   2   3
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN  56
4 NaN  56   9
5  61   9  12
6   9  12  15
7  12  15  11

[8 rows x 3 columns]

In [44]: result = roller.apply(f).reindex_like(roller)

In [49]: result.index = result.index.values-len(result.index)+1

In [50]: result
Out[50]: 
     1   2   3
-7 NaN NaN NaN
-6 NaN NaN NaN
-5 NaN NaN NaN
-4 NaN NaN  56
-3 NaN  56   9
-2  61   9  12
-1   9  12  15
 0  12  15  11

[8 rows x 3 columns]

关于Python Pandas - 将绝对周期转换为相对周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22670904/

相关文章:

pandas - 如何在 Pandas 中将索引转换为日期时间?

python - Pandas - 将单独的帧与每月的列相加

python - Pandas multiIndex 完全复制到数据帧切片

python - 将 2 个不同年份的 .resample(D).size() 绘制到一张图表中?

r - 将小数年份和一年中的某一天转换为 R 中的日期

python - 各时段活跃ID数

python - 使用 FFT 计算滤波器 (b,a,x,zi)

Python逐行实时迭代linux命令输出

python - 查找页面上文本的部分内容,然后使用 Selenium 在 Python 中返回该 <div> 的完整内容

python-3.x - 带有圆角的 Seaborn 条形图