如何计算给定 NumPy 数组中所有元素的负数值?
在本文中,我们将了解如何计算给定 NumPy 数组中所有元素的负值。因此,负值实际上是添加到任何数字时变为0的数字。
例子:
如果我们取一个数为 4,那么 -4 是它的负数,因为当我们将 -4 加到 4 时,我们得到的总和为 0。现在让我们再举一个例子,假设我们取一个数字 -6 现在当我们给它加上 +6然后总和变为零。因此+6是-6的负值。现在假设我们有一个数字数组:
A = [1,2,3,-1,-2,-3,0]
So, the negative value of A is
A'=[-1,-2,-3,1,2,3,0].
因此,为了找到元素的负数值,我们必须使用 NumPy 库的numpy.negative()函数。
Syntax: numpy.negative(arr, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘negative’)
Return: [ndarray or scalar] Returned array or scalar = -(input arr or scalar )
现在,让我们看一下示例:
示例 1:
Python3
# importing library
import numpy as np
# creating a array
x = np.array([-1, -2, -3,
1, 2, 3, 0])
print("Printing the Original array:",
x)
# converting array elements to
# its corresponding negative value
r1 = np.negative(x)
print("Printing the negative value of the given array:",
r1)
Python3
# importing library
import numpy as np
# creating a numpy 2D array
x = np.array([[1, 2],
[2, 3]])
print("Printing the Original array Content:\n",
x)
# converting array elements to
# its corresponding negative value
r1 = np.negative(x)
print("Printing the negative value of the given array:\n",
r1)
输出:
Printing the Original array: [-1 -2 -3 1 2 3 0]
Printing the negative value of the given array: [ 1 2 3 -1 -2 -3 0]
示例 2:
Python3
# importing library
import numpy as np
# creating a numpy 2D array
x = np.array([[1, 2],
[2, 3]])
print("Printing the Original array Content:\n",
x)
# converting array elements to
# its corresponding negative value
r1 = np.negative(x)
print("Printing the negative value of the given array:\n",
r1)
输出:
Printing the Original array Content:
[[1 2]
[2 3]]
Printing the negative value of the given array:
[[-1 -2]
[-2 -3]]