101

有没有一种简单的方法可以用 0 替换数组中的所有负值?

我对如何使用 NumPy 数组进行了完整的了解。

例如

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

我需要返回

[1, 2, 3, 0, 5]

a < 0给出:

[False, False, False, True, False]

这就是我卡住的地方——如何使用这个数组来修改原始数组。

4

6 回答 6

151

你已经成功了一半。尝试:

In [4]: a[a < 0] = 0

In [5]: a
Out[5]: array([1, 2, 3, 0, 5])
于 2012-04-26T14:06:45.930 回答
95

尝试numpy.clip

>>> import numpy
>>> a = numpy.arange(-10, 10)
>>> a
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])
>>> a.clip(0, 10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

您只能使用 剪辑下半部分clip(0)

>>> a = numpy.array([1, 2, 3, -4, 5])
>>> a.clip(0)
array([1, 2, 3, 0, 5])

您只能使用 剪辑上半部分clip(max=n)。(这比我之前的建议要好得多,它涉及传递NaN给第一个参数并out用于强制类型。):

>>> a.clip(max=2)
array([ 1,  2,  2, -4,  2])

另一种有趣的方法是使用where

>>> numpy.where(a <= 2, a, 2)
array([ 1,  2,  2, -4,  2])

最后,考虑aix的答案。我更喜欢clip简单的操作,因为它是自记录的,但他的回答更适合更复杂的操作。

于 2012-04-26T14:05:31.123 回答
10

另一个不使用 numpy 的极简 Python 解决方案:

[0 if i < 0 else i for i in a]

无需定义任何额外的功能。

a = [1, 2, 3, -4, -5.23, 6]
[0 if i < 0 else i for i in a]

产量:

[1, 2, 3, 0, 0, 6]
于 2012-04-26T16:36:27.967 回答
4

还有另一种可能:

In [2]: a = array([1, 2, 3, -4, 5])

In [3]: where(a<0, 0, a)
Out[3]: array([1, 2, 3, 0, 5])
于 2015-07-10T14:20:57.350 回答
2

这是一种在没有 NumPy 的情况下在 Python 中实现的方法。创建一个返回所需内容的函数,并使用列表推导或map函数。

>>> a = [1, 2, 3, -4, 5]

>>> def zero_if_negative(x):
...   if x < 0:
...     return 0
...   return x
...

>>> [zero_if_negative(x) for x in a]
[1, 2, 3, 0, 5]

>>> map(zero_if_negative, a)
[1, 2, 3, 0, 5]
于 2012-04-26T14:11:13.167 回答
0

基准使用numpy

%%timeit
a = np.random.random(1000) - 0.5
b = np.maximum(a,0)
# 18.2 µs ± 204 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
a = np.random.random(1000) - 0.5
a[a < 0] = 0
# 19.6 µs ± 304 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
a = np.random.random(1000) - 0.5
b = np.where(a<0, 0, a)
# 21.1 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%%timeit
a = np.random.random(1000) - 0.5
b = a.clip(0)
# 37.7 µs ± 124 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

令人惊讶的是,np.maximum击败了@NPE answer


警告:

  1. os[os < 0] = 0比 快,np.where()但不受numba. 但无论如何,np.maximum()这是我发现的最快的。

  2. np.maximum()不同于np.max()np.amax()np.maximum()可以vector与单个值进行比较。

于 2022-01-31T09:17:58.883 回答