python - 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
这个函数的计算需要比较长的时间。有没有更快的实现来做到这一点?
解决方案
我不确定为什么您的计算需要这么长时间,希望这有助于澄清,例如您的数组列表是这样的:
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])
推荐阅读
- msbuild - How to use nuget.targets file to save two DLLs with same name but different target architecture into output respective folders in output directory
- android - DJI Mobile 示例 Sdk Android - Sdk 注册失败 [dji-sdk]
- visual-studio - Visual Studio 中是否有复制值的快捷方式?
- c - 为什么字符串开头没有空格时它不起作用?
- c# - 按数字顺序从文件中排序项目并检查重复项 C#
- r - Ggplot2:如何为单个值设置颜色并让其他值自动着色
- amazon-web-services - 在转发到 api 资源之前在 AWS 负载均衡器中授权 Cognito 访问令牌的方式
- macos - linux和mac的环境变量格式一样吗?
- java - 卡夫卡连接。如何为连接器启用 jmx 指标
- mongodb - MongoDB 程序化集合创建/删除成本