Skip to main content
 首页 » 编程设计

python之提取 DataFrame 的扩展窗口(numpy strided)

2024年09月07日7虾米哥

(与 this answer 相关)

给定一个 df ,我期待得到 df.expanding() 的结果并使用 df 对此执行一些多元操作(涉及 .apply() 的多个列的操作同时在扩展的行窗口上进行) .事实证明这是不可能的。

所以,就像上面链接的答案一样,我需要使用 numpy.as_strides的 df .除了,与上面链接的问题相反,使用 strides 来扩展我的 df 的 View 。 ,而不是滚动窗口(扩展窗口的左侧固定,右侧逐渐向右移动)。

考虑这个df :

import numpy 
import pandas 
 
 
df = pandas.DataFrame(numpy.random.normal(0, 1, [100, 2]), columns=['size_A', 'size_B']).cumsum(axis=0) 

考虑此代码以提取 W 的滚动窗口那行 df (这来自上面的答案):

def get_sliding_window(df, W): 
    a = df.values                  
    s0,s1 = a.strides 
    m,n = a.shape 
    return numpy.lib.stride_tricks\ 
               .as_strided(a,shape=(m-W+1,W,n),strides=(s0,s0,s1)) 
 
roll_window = get_sliding_window(df, W = 3) 
roll_window[2]  

现在我要修改get_sliding_window让它返回 df 的扩展窗口(而不是滚动窗口):

def get_expanding_window(df): 
    a = df.values                  
    s0,s1 = a.strides 
    m,n = a.shape 
    out = numpy.lib.stride_tricks\ 
               .as_strided(a, shape=(m,m,n),strides=(s0,s0,s1)) 
    return out 
 
expg_window = get_expanding_window(df) 
expg_window[2] 

但我没有使用 as_strided 的参数正确地:我似乎无法获得正确的矩阵——那将是这样的:

[df.iloc[0:1].values ,df.iloc[0:2].values, df.iloc[0:3].values,...]   

编辑:

@ThomasKühn 在评论中建议使用列表理解。 这将解决问题,但速度太慢。费用是多少?

一个向量值函数,我们可以比较成本 列表理解 .expand() .它不小:

numpy.random.seed(123) 
df = pandas.DataFrame((numpy.random.normal(0, 1, 10000)), columns=['Value']) 
%timeit method_1 = numpy.array([df.Value.iloc[range(j + 1)].sum() for j in range(df.shape[0])]) 

给出:

6.37 s ± 219 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 

与 .expanding() 相比:

%timeit method_2 = df.expanding(0).apply(lambda x: x.sum()) 

给出:

35.5 ms ± 356 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 

最后,关于我要解决的问题有更多的细节 在对 this 的评论中问题。

请您参考如下方法:

我写了几个函数,它们都应该做同样的事情,但需要不同的时间来完成任务:

import timeit 
import numba as nb 
 
x = np.random.normal(0,1,(10000,2)) 
def f1(): 
    res = [np.sum(x[:i,0] > x[i,1]) for i in range(x.shape[0])] 
    return res 
 
def f2(): 
    buf = np.empty(x.shape[0]) 
    res = np.empty(x.shape[0]) 
    for i in range(x.shape[0]): 
        buf[:i] = x[:i,0] > x[i,1] 
        res[i] = np.sum(buf[:i]) 
    return res 
 
def f3(): 
    res = np.empty(x.shape[0]) 
    for i in range(x.shape[0]): 
        res[i] = np.sum(x[:i,0] > x[i,1]) 
    return res 
 
 
@nb.jit(nopython=True) 
def f2_nb(): 
    buf = np.empty(x.shape[0]) 
    res = np.empty(x.shape[0]) 
    for i in range(x.shape[0]): 
        buf[:i] = x[:i,0] > x[i,1] 
        res[i] = np.sum(buf[:i]) 
    return res 
 
@nb.jit(nopython=True) 
def f3_nb(): 
    res = np.empty(x.shape[0]) 
    for i in range(x.shape[0]): 
        res[i] = np.sum(x[:i,0] > x[i,1]) 
    return res 
 
##checking that all functions give the same result: 
print('checking correctness') 
print(np.all(f1()==f2())) 
print(np.all(f1()==f3())) 
print(np.all(f1()==f2_nb())) 
print(np.all(f1()==f3_nb())) 
 
print('+'*50) 
print('performance tests') 
print('f1()')         
print(min(timeit.Timer( 
    'f1()', 
    setup = 'from __main__ import f1,x', 
).repeat(7,10))) 
 
print('-'*50) 
print('f2()') 
print(min(timeit.Timer( 
    'f2()', 
    setup = 'from __main__ import f2,x', 
).repeat(7,10))) 
 
print('-'*50) 
print('f3()') 
print(min(timeit.Timer( 
    'f3()', 
    setup = 'from __main__ import f3,x', 
).repeat(7,10))) 
 
print('-'*50) 
print('f2_nb()') 
print(min(timeit.Timer( 
    'f2_nb()', 
    setup = 'from __main__ import f2_nb,x', 
).repeat(7,10))) 
 
print('-'*50) 
print('f3_nb()') 
print(min(timeit.Timer( 
    'f3_nb()', 
    setup = 'from __main__ import f3_nb,x', 
).repeat(7,10))) 

如您所见,差异并不大,但在性能上存在一些差异。最后两个函数只是早期函数的“重复”,但使用了 numba 优化。速度测试的结果是

checking correctness 
True 
True 
True 
True 
++++++++++++++++++++++++++++++++++++++++++++++++++ 
performance tests 
f1() 
2.02294262702344 
-------------------------------------------------- 
f2() 
3.0964318679762073 
-------------------------------------------------- 
f3() 
1.9573561699944548 
-------------------------------------------------- 
f2_nb() 
1.3796060049789958 
-------------------------------------------------- 
f3_nb() 
0.48667875200044364 

如您所见,差异并不大,但在最慢和最快的函数之间,加速比大约是 6 倍。希望这会有所帮助。