计算 NumPy 数组中所有元素的倒数
在本文中,让我们讨论如何计算给定 NumPy 数组的所有元素的倒数。
方法一:通过reciprocal_arr = 1/arr语句,我们可以将arr的每一个元素都转换成倒数,并保存到reciprocal_arr中。但是有个catch,如果“arr”的任何一个元素为0,就会报错。所以请注意不要将任何数组传递给包含 0 的 reciprocal_arr。
示例 1:
Python
# PROGRAM TO FIND RECIPROCAL OF EACH
# ELEMENT OF NUMPY ARRAY
import numpy as np
lst = [22, 34, 65, 50, 7]
arr = np.array(lst)
reciprocal_arr = 1/arr
print(reciprocal_arr)
Python
# PROGRAM TO FIND RECIPROCAL OF EACH
# ELEMENT OF NUMPY ARRAY
import numpy as np
tup = (12, 87, 77, 90, 57, 34)
arr = np.array(tup)
reciprocal_arr = 1/arr
print(reciprocal_arr)
Python3
# program to compute the Reciprocal
# for all elements in a given array
# with the help of numpy.reciprocal()
import numpy as np
arr = [2, 1.5, 8, 9, 0.2]
reciprocal_arr = np.reciprocal(arr)
print(reciprocal_arr)
Python3
# program to compute the Reciprocal for
# all elements in a given array with the
# help of numpy.reciprocal()
import numpy as np
arr = (3, 6.5, 1, 5.9, 8)
reciprocal_arr = np.reciprocal(arr)
print(reciprocal_arr)
输出:
[0.04545455 0.02941176 0.01538462 0.02 0.14285714]
示例 2:
Python
# PROGRAM TO FIND RECIPROCAL OF EACH
# ELEMENT OF NUMPY ARRAY
import numpy as np
tup = (12, 87, 77, 90, 57, 34)
arr = np.array(tup)
reciprocal_arr = 1/arr
print(reciprocal_arr)
输出:
[0.08333333 0.01149425 0.01298701 0.01111111 0.01754386 0.02941176]
方法二:使用 numpy.reciprocal() 方法
Numpy 库还提供了一种简单的方法来查找数组中每个元素的倒数。 reciprocal() 方法可以很容易地用于创建一个新数组,每个数组都包含每个元素的倒数。
示例 1:
Python3
# program to compute the Reciprocal
# for all elements in a given array
# with the help of numpy.reciprocal()
import numpy as np
arr = [2, 1.5, 8, 9, 0.2]
reciprocal_arr = np.reciprocal(arr)
print(reciprocal_arr)
输出:
[0.5 0.66666667 0.125 0.11111111 5. ]
示例 2:
Python3
# program to compute the Reciprocal for
# all elements in a given array with the
# help of numpy.reciprocal()
import numpy as np
arr = (3, 6.5, 1, 5.9, 8)
reciprocal_arr = np.reciprocal(arr)
print(reciprocal_arr)
输出:
[0.33333333 0.15384615 1. 0.16949153 0.125 ]