左对齐 pandas 滚动对象 [英] Left-align a pandas rolling object
问题描述
使用大熊猫0.18.1,我想获取一栏数据框的滚动平均值.从0.18.0版开始,这是通过rolling()对象完成的.这些滚动对象的默认设置是右对齐的.您可以传递一个布尔参数,center = True,以将滚动对象与中心值对齐,但是似乎没有办法将其左对齐.这是一个示例:
Using pandas 0.18.1, I'd like to take the rolling average of a one-column dataframe. Since version 0.18.0, this is done with rolling() objects. The default for these rolling objects is to be right-justified. There is a boolean argument you can pass, center=True, to align the rolling object to the center value, but there doesn't seem to be a way to left-align it. Here's an example:
df = pandas.DataFrame({'A': [2,3,6,8,20, 27]})
df
A
0 2
1 3
2 6
3 8
4 20
5 27
标准方法会自动向右对齐,因此前两个变量的窗口大小为三时没有任何值:
The standard method automatically aligns to the right, so there's no value at the first two indecies with a window of size three:
df.rolling(window=3).mean()
A
0 NaN
1 NaN
2 3.666667
3 5.666667
4 11.333333
5 18.333333
我们可以像这样对操作进行居中对齐:
We can center-align the operation like this:
df.rolling(window=3).mean(center=True)
A
0 NaN
1 3.666667
2 5.666667
3 11.333333
4 18.333333
5 NaN
但是我要找的是这个
df.rolling(3).mean()
A
0 3.666667
1 5.666667
2 11.333333
3 18.333333
4 NaN
5 NaN
我可以通过以下方法完成此任务:使用默认的右对齐方式,然后对其重新编制索引,或者通过反转行的顺序,然后将其右对齐",但是这些都是应解决的方法简单直接的操作.
I can accomplish this by doing it with the default right alignment, and then re-indexing it, or by reversing the order of the rows and then doing it "right-aligned" but these are work-arounds for what should be a straight-forward operation.
推荐答案
I think you can use shift
:
a = df.rolling(window=3).mean().shift(-2)
print (a)
A
0 3.666667
1 5.666667
2 11.333333
3 18.333333
4 NaN
5 NaN
这篇关于左对齐 pandas 滚动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!