【问题标题】:Pandas: Can you access rolling window items熊猫:你能访问滚动窗口项目吗
【发布时间】:2017-01-15 09:18:30
【问题描述】:

你能访问熊猫滚动窗口对象吗?

rs = pd.Series(range(10))
rs.rolling(window = 3)

#print's 
Rolling [window=3,center=False,axis=0]

我可以分组吗?:

[0,1,2]
[1,2,3]
[2,3,4]

【问题讨论】:

标签: python pandas


【解决方案1】:

我将首先说这是到达into the internal impl。但是,如果您真的想像 pandas 一样计算索引器。

你需要v0.19.0rc1(即将发布),你可以conda install -c pandas pandas=0.19.0rc1

In [41]: rs = pd.Series(range(10))

In [42]: rs
Out[42]: 
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: int64

# this reaches into an internal implementation
# the first 3 is the window, then second the minimum periods we
# need    
In [43]: start, end, _, _, _, _ = pandas._window.get_window_indexer(rs.values,3,3,None,use_mock=False)

# starting index
In [44]: start
Out[44]: array([0, 0, 0, 1, 2, 3, 4, 5, 6, 7])

# ending index
In [45]: end
Out[45]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

# windo size
In [3]: end-start
Out[3]: array([1, 2, 3, 3, 3, 3, 3, 3, 3, 3])

# the indexers
In [47]: [np.arange(s, e) for s, e in zip(start, end)]
Out[47]: 
[array([0]),
 array([0, 1]),
 array([0, 1, 2]),
 array([1, 2, 3]),
 array([2, 3, 4]),
 array([3, 4, 5]),
 array([4, 5, 6]),
 array([5, 6, 7]),
 array([6, 7, 8]),
 array([7, 8, 9])]

所以这在固定窗口情况下有点微不足道,这在可变窗口情况下变得非常有用,例如在 0.19.0 中,您可以指定 2S 之类的内容,例如按时间聚合。

综上所述,获取这些索引器并不是特别有用。您通常希望对结果一些事情。这就是聚合函数的重点,如果您想进行一般聚合,则可以使用 .apply

【讨论】:

  • 我喜欢这个想法,但我无法拨打pd._window.get_window_indexer() 工作。我不断收到module 'pandas' has no attribute '_window'。知道如何解决这个问题吗?还要添加指向get_window_indexer() 源的链接,因为它的文档不会出现在我的笔记本中。
【解决方案2】:

这是一种解决方法,但正在等待看看是否有人有 pandas 解决方案:

def rolling_window(a, step):
    shape   = a.shape[:-1] + (a.shape[-1] - step + 1, step)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

rolling_window(rs, 3)

array([[ 0,  1,  2],
       [ 1,  2,  3],
       [ 2,  3,  4],
       [ 3,  4,  5],
       [ 4,  5,  6],
       [ 5,  6,  7],
       [ 6,  7,  8],
       [ 7,  8,  9],
       [ 8,  9, 10]])

【讨论】:

    猜你喜欢
    • 2017-03-30
    • 2020-04-21
    • 2021-03-30
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2021-04-06
    • 2016-11-19
    • 2016-09-10
    相关资源
    最近更新 更多