没有步长的选择吗pandas.DataFrame.rolling?有没有其他功能可以帮我完成这个任务?

2024-10-02 18:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

在R中,你可以用一个指定的窗口来计算滚动平均值,这个窗口每次可以移动指定的量。在

然而,也许我在任何地方都找不到它,但似乎在pandas或其他python库中都找不到它?在

有没有人知道解决这个问题的办法。我给你举个例子来说明我的意思:

example

这里我们有半个月的数据,我在计算两个月的移动平均值,每个月移动一次。在

所以在R中我会做一些类似的事情:two_month__movavg=rollapply(mydata,4,mean,by = 2,na.pad = FALSE) 在Python中没有等价物吗?在

编辑1:

DATE  A DEMAND   ...     AA DEMAND  A Price
    0  2006/01/01 00:30:00  8013.27833   ...     5657.67500    20.03
    1  2006/01/01 01:00:00  7726.89167   ...     5460.39500    18.66
    2  2006/01/01 01:30:00  7372.85833   ...     5766.02500    20.38
    3  2006/01/01 02:00:00  7071.83333   ...     5503.25167    18.59
    4  2006/01/01 02:30:00  6865.44000   ...     5214.01500    17.53

Tags: 数据pandas地方mean事情例子平均值two
2条回答

现在这对于1D数据数组来说有点过头了,但是您可以简化它并提取出所需的内容。因为熊猫可以依赖numpy,所以您可能需要检查一下它们的滚动/跨步功能是否实现。 20个序列号的结果。一个7天的窗口,大步/滑动2

    z = np.arange(20)
    z   #array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
    s = stride(z, (7,), (2,))

np.mean(s, axis=1)  # array([ 3.,  5.,  7.,  9., 11., 13., 15.])

下面是我在没有文档主要部分的情况下使用的代码。它源于许多在numpy中实现的跨接函数,可以在这个站点上找到。有变体和化身,这只是另一个。在

^{pr2}$

我没有指出,您可以创建一个可以作为列附加到pandas中的输出。回到上面使用的原始定义

nans = np.full_like(z, np.nan, dtype='float')  # z is the 20 number sequence
means = np.mean(s, axis=1)   # results from the strided mean
# assign the means to the output array skipping the first and last 3 and striding by 2

nans[3:-3:2] = means        

nans # array([nan, nan, nan,  3., nan,  5., nan,  7., nan,  9., nan, 11., nan, 13., nan, 15., nan, nan, nan, nan])

你可以再次使用滚动,只需要一点工作与你分配索引

这里by = 2

by = 2

df.loc[df.index[np.arange(len(df))%by==1],'New']=df.Price.rolling(window=4).mean()
df
    Price    New
0      63    NaN
1      92    NaN
2      92    NaN
3       5  63.00
4      90    NaN
5       3  47.50
6      81    NaN
7      98  68.00
8     100    NaN
9      58  84.25
10     38    NaN
11     15  52.75
12     75    NaN
13     19  36.75

相关问题 更多 >