如何将负元素转换为零而没有循环? [英] How to transform negative elements to zero without a loop?

查看:89
本文介绍了如何将负元素转换为零而没有循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像这样的数组

If I have an array like

a = np.array([2, 3, -1, -4, 3])

我要将所有否定元素设置为零:[2, 3, 0, 0, 3].如何在没有显式for的情况下使用numpy?例如,我需要在计算中使用修改后的a

I want to set all the negative elements to zero: [2, 3, 0, 0, 3]. How to do it with numpy without an explicit for? I need to use the modified a in a computation, for example

c = a * b

其中b是另一个数组,其长度与原始a

where b is another array with the same length of the original a

import numpy as np
from time import time

a = np.random.uniform(-1, 1, 20000000)
t = time(); b = np.where(a>0, a, 0); print ("1. ", time() - t)
a = np.random.uniform(-1, 1, 20000000)
t = time(); b = a.clip(min=0); print ("2. ", time() - t)
a = np.random.uniform(-1, 1, 20000000)
t = time(); a[a < 0] = 0; print ("3. ", time() - t)
a = np.random.uniform(-1, 1, 20000000)
t = time(); a[np.where(a<0)] = 0; print ("4. ", time() - t)
a = np.random.uniform(-1, 1, 20000000)
t = time(); b = [max(x, 0) for x in a]; print ("5. ", time() - t)

  1. 1.38629984856
  2. 0.516846179962<-更快的a.clip(min = 0);
  3. 0.615426063538
  4. 0.944557905197
  5. 51.7364809513

推荐答案

a = a.clip(min=0)

这篇关于如何将负元素转换为零而没有循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆