np.sum 需要很长时间才能运行

问题描述 投票:0回答:1

我的代码执行时间很长。查了一下,发现大部分时间都花在了下面的循环中。我该如何优化这个循环?

for j in range(6):
    x1 = np.sum(abs(refy1[j:refy1.shape[0]] - ref1[:ref1.shape[0] - j]))
    y1[0, j] = x1
    z1[0, j] = -j

其中,

refy1
ref1
是维度为1024*1的向量 并且,
y1
z1
是空数组

我在Cython上运行了相应的循环,让它跑得更快,可惜并没有提升

python numpy cython
1个回答
0
投票

您可以在

refy1
ref1
数组上应用滚动窗口。

然后,从第一个

x1
卷计算
j

import numpy as np
import pandas as pd

n = 1024 # assumes refy1 and ref1 have the same shape.
refy1 = pd.DataFrame(np.arange(1, n))
ref1 = pd.DataFrame(np.arange(1, n))

y1 = np.zeros([1, 6])
z1 = np.zeros([1, 6])

j = 6
indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=n)

refy1_roll = refy1.rolling(indexer, min_periods=1)
ref1_roll = (
    ref1.sort_index(
        ascending=False
    ).reset_index(
        drop=True
    ).rolling(
        indexer, min_periods=1
    )
)

# Operate row-wise on the first j rolls.
x1 = np.array([
    np.sum(abs(a - b)) 
    for _, a, b in zip(range(j), refy1_roll, ref1_roll)
])

y1[0, :j] = x1[:j].transpose()
z1[0, :j] = -1 * np.arange(0, j)
© www.soinside.com 2019 - 2024. All rights reserved.