使用 NumPy 對陣列的元素進行指定值的冪運算,並在不同的資料型別中顯示結果
要對陣列的元素進行指定值的冪運算,可以使用 Python 中的 **numpy.power()** 方法。這裡,第一個引數是底數,第二個引數是指數。**dtype** 引數用於設定輸出資料型別。
將 x1 中的每個底數都提升到 x2 中位置對應的冪。x1 和 x2 必須能夠廣播到相同的形狀。整數型別提升到負整數冪將引發 ValueError。負值提升到非整數值將返回 nan。要獲得複數結果,請將輸入轉換為複數,或將 dtype 指定為複數。
此條件將廣播到輸入上。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他位置,out 陣列將保留其原始值。請注意,如果透過預設的 out=None 建立未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化狀態。
步驟
首先,匯入所需的庫:
import numpy as np
建立一個數組:
arr = np.array([5, 10, 25, 30, 40, 50])
顯示陣列:
print("Array...
", arr)
獲取陣列的型別:
print("
Our Array type...
", arr.dtype)
獲取陣列的維度:
print("
Our Array Dimension...
",arr.ndim)
獲取陣列的形狀:
print("
Our Array Shape...
",arr.shape)
設定指數:
p = 2.5
要對陣列的元素進行指定值的冪運算,可以使用 Python 中的 numpy.power() 方法。這裡,第一個引數是底數,第二個引數是指數。dtype 引數用於設定輸出資料型別:
print("
Result...
",np.power(arr, p, dtype = complex))
示例
import numpy as np # Create an array arr = np.array([5, 10, 25, 30, 40, 50]) # Display the array print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Set the exponent p = 2.5 # To power array elements of an array with a given value, use the numpy.power() method in Python # Here, the 1st parameter is the base and the 2nd exponents # The dtype parameter is used to set the output datatype print("
Result...
",np.power(arr, p, dtype = complex))
輸出
Array... [ 5 10 25 30 40 50] Our Array type... int64 Our Array Dimension... 1 Our Array Shape... (6,) Result... [ 55.90169944+0.j 316.22776602+0.j 3125. +0.j 4929.50301755+0.j 10119.28851254+0.j 17677.66952966+0.j]
廣告