将数组操作转换为纯 numpy 方法

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

我该如何翻译这段代码:

rose_number = np.copy(rosehrs)

for a in range(0,1597):
    for b in range(0,2145):
        for c in range(0,64):
            rose_number[a][b][c] = round((rosehrs[a][b][c]/totalhrs[a][b])*100,2)

进入 numpy 函数?也许使用

np.divide
where
的一个选项,但我不确定所需的操作。

python numpy
1个回答
0
投票

您的输入并不完全清楚,但您很可能可以使用以下方法对您的操作进行矢量化:

out = np.round(rosehrs/totalhrs[..., None]*100, 2)

随机举例:

np.random.seed(0)
rosehrs = np.random.random((1597, 2145, 64))
totalhrs = np.random.random((1597, 2145))

这个运行时间约为1.4秒:

1.41 s ± 65.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
© www.soinside.com 2019 - 2024. All rights reserved.