滑动窗户上的熊猫滚动计算(间隔不均匀)

rad*_*lus 12 python pandas

考虑一下你有一些不均匀的时间序列数据:

import pandas as pd
import random as randy
ts = pd.Series(range(1000),index=randy.sample(pd.date_range('2013-02-01 09:00:00.000000',periods=1e6,freq='U'),1000)).sort_index()
print ts.head()


2013-02-01 09:00:00.002895    995
2013-02-01 09:00:00.003765    499
2013-02-01 09:00:00.003838    797
2013-02-01 09:00:00.004727    295
2013-02-01 09:00:00.006287    253
Run Code Online (Sandbox Code Playgroud)

假设我想在1毫秒的窗口上进行滚动总和来得到这个:

2013-02-01 09:00:00.002895    995
2013-02-01 09:00:00.003765    499 + 995
2013-02-01 09:00:00.003838    797 + 499 + 995
2013-02-01 09:00:00.004727    295 + 797 + 499
2013-02-01 09:00:00.006287    253
Run Code Online (Sandbox Code Playgroud)

目前,我把所有东西都重新投入了多头并在cython中完成,但这在纯大熊猫中是否可行?我知道你可以做类似.asfreq('U')之类的东西,然后填充并使用传统的功能,但是一旦你拥有超过玩具的行数,这就无法扩展.

作为参考,这是一个hackish,而不是快速的Cython版本:

%%cython
import numpy as np
cimport cython
cimport numpy as np

ctypedef np.double_t DTYPE_t

def rolling_sum_cython(np.ndarray[long,ndim=1] times, np.ndarray[double,ndim=1] to_add, long window_size):
    cdef long t_len = times.shape[0], s_len = to_add.shape[0], i =0, win_size = window_size, t_diff, j, window_start
    cdef np.ndarray[DTYPE_t, ndim=1] res = np.zeros(t_len, dtype=np.double)
    assert(t_len==s_len)
    for i in range(0,t_len):
        window_start = times[i] - win_size
        j = i
        while times[j]>= window_start and j>=0:
            res[i] += to_add[j]
            j-=1
    return res   
Run Code Online (Sandbox Code Playgroud)

在更大的系列中展示这一点:

ts = pd.Series(range(100000),index=randy.sample(pd.date_range('2013-02-01 09:00:00.000000',periods=1e8,freq='U'),100000)).sort_index()

%%timeit
res2 = rolling_sum_cython(ts.index.astype(int64),ts.values.astype(double),long(1e6))
1000 loops, best of 3: 1.56 ms per loop
Run Code Online (Sandbox Code Playgroud)

sig*_*ker 11

您可以使用cumsum和二分查找来解决此类问题.

from datetime import timedelta

def msum(s, lag_in_ms):
    lag = s.index - timedelta(milliseconds=lag_in_ms)
    inds = np.searchsorted(s.index.astype(np.int64), lag.astype(np.int64))
    cs = s.cumsum()
    return pd.Series(cs.values - cs[inds].values + s[inds].values, index=s.index)

res = msum(ts, 100)
print pd.DataFrame({'a': ts, 'a_msum_100': res})


                            a  a_msum_100
2013-02-01 09:00:00.073479  5           5
2013-02-01 09:00:00.083717  8          13
2013-02-01 09:00:00.162707  1          14
2013-02-01 09:00:00.171809  6          20
2013-02-01 09:00:00.240111  7          14
2013-02-01 09:00:00.258455  0          14
2013-02-01 09:00:00.336564  2           9
2013-02-01 09:00:00.536416  3           3
2013-02-01 09:00:00.632439  4           7
2013-02-01 09:00:00.789746  9           9

[10 rows x 2 columns]
Run Code Online (Sandbox Code Playgroud)

您需要一种处理NaN的方法,根据您的应用,您可能需要滞后时间的主导值(即使用kdb + bin与np.searchsorted之间的差异).

希望这可以帮助.


Kev*_*ang 7

这是一个老问题,但对于那些从谷歌偶然发现这一点的人:在pandas 0.19中,这是内置的功能

http://pandas.pydata.org/pandas-docs/stable/computation.html#time-aware-rolling

因此,要获得1毫秒的窗口,您可能会看到滚动对象

dft.rolling('1ms')
Run Code Online (Sandbox Code Playgroud)

总和将是

dft.rolling('1ms').sum()
Run Code Online (Sandbox Code Playgroud)