Use cases of `numpy.positive`



numpy(版本 1.13+ (中有一个 positive 函数,它似乎什么都不做:

In [1]: import numpy as np                                                                               
In [2]: A = np.array([0, 1, -1, 1j, -1j, 1+1j, 1-1j, -1+1j, -1-1j, np.inf, -np.inf])                     
In [3]: A == np.positive(A)                                                                              
Out[3]: 
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True])

文件说:Returned array or scalar: `y = +x`

此功能有哪些用例?

这个函数的用例可能很少。之所以提供它,是因为每个 python 运算符在 numpy 中都公开为 ufunc:

  • 一元+np.positive
  • 一元-np.negative
  • 二进制+np.add
  • 二进制-np.subtract
  • 等。。。

正如文档所述,并在另一个答案中指出,np.positive会像np.copy一样制作数据的副本,但有两个警告:

  1. 它可以更改输入的dtype

  2. 它仅针对算术类型定义。例如,如果您尝试在布尔数组上调用它,您将获得

     UFuncTypeError: ufunc 'positive' did not contain a loop with signature matching types dtype('bool') -> dtype('bool')
    

另一件事是,由于positive是一个ufunc,它可以就地工作,使其成为算术类型的有效无操作函数:

np.positive(x, out=x)

如果你有一个向量x,那么np.positive(x)给你,+1*(x)np.negative(x)给你-1*(x)

np.positive([-1,0.7])
output: array([-1. ,  0.7])

np.negative([-1.5,0.7])
output:array([ 1.5, -0.7])

np.positive(np.array([0, 1, -1, 1j, -1j, 1+1j, 1-1j, -1+1j, -1-1j, np.inf, -np.inf]))
output: array([  0.+0.j,   1.+0.j,  -1.+0.j,   0.+1.j,  -0.-1.j,   1.+1.j,
         1.-1.j,  -1.+1.j,  -1.-1.j,  inf+0.j, -inf+0.j])

np.negative(np.array([0, 1, -1, 1j, -1j, 1+1j, 1-1j, -1+1j, -1-1j, np.inf, -np.inf]))
output: array([ -0.-0.j,  -1.-0.j,   1.-0.j,  -0.-1.j,   0.+1.j,  -1.-1.j,
        -1.+1.j,   1.-1.j,   1.+1.j, -inf-0.j,  inf-0.j])

不过用例取决于。一旦用例,它是x1 = copy(x)的替代方案。它会创建一个重复的数组供您使用。

最新更新