首页 > 解决方案 > Numpy 快速 for 循环

问题描述

我有一个名为“y”的列表,其中包含 8 个形状为 (180000,) 的 numpy 数组现在我想创建一个名为“Collision”的新 numpy 数组,其形状相同,计算 y 有多少个值不为 0。见以下示例:

import numpy as np
collisions = np.zeros(len(y[0]), dtype=np.uint8)
for yi in y:
    collisions[np.where(yi > 0)] += 1

这个函数的计算需要比较长的时间。有没有更快的实现来做到这一点?

标签: pythonnumpy

解决方案


我不确定为什么您的计算需要这么长时间,希望这有助于澄清,例如您的数组列表是这样的:

import numpy as np
y = [np.random.normal(0,1,180000) for i in range(8)]

运行您的代码,它可以正常工作:

collisions = np.zeros(len(y[0]), dtype=np.uint8)
for yi in y:
    collisions[np.where(yi > 0)] += 1

collisions
array([4, 2, 4, ..., 4, 4, 5], dtype=uint8)

你可以像这样快一点,基本上让你的数组列表成为一个矩阵并做一个> 0的行总和,但我没有看到上面的问题:

(np.array(y)>0).sum(axis=0)

array([4, 2, 4, ..., 4, 4, 5])

推荐阅读