使用Numpy設定第一個陣列元素,使其逐元素對應第二個陣列中的冪


要將第一個陣列的元素逐元素地提高到第二個陣列的冪,請在Python中使用**numpy.power()**方法。這裡,第一個引數是底數,第二個引數是指數。

將x1中的每個底數提高到x2中位置對應的冪。x1和x2必須可廣播到相同的形狀。整數型別提高到負整數冪將引發ValueError。負值提高到非整數值將返回nan。要獲得複數結果,請將輸入轉換為複數,或指定dtype為複數。

out是儲存結果的位置。如果提供,它必須具有輸入廣播到的形狀。如果沒有提供或為None,則返回一個新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出的數量。

步驟

首先,匯入所需的庫:

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, 3, 2, 3, 2, 3]

要將第一個陣列元素逐元素地提高到第二個陣列的冪,請使用numpy.power()方法。這裡,第一個引數是底數,第二個引數是指數:

print("
Result...
",np.power(arr, p))

示例

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, 3, 2, 3, 2, 3] # To set the first array elements raised to powers from second array, element-wise, use the numpy.power() method in Python # Here, the 1st parameter is the base and the 2nd exponents print("
Result...
",np.power(arr, p))

輸出

Array...
[ 5 10 25 30 40 50]

Our Array type...
int64

Our Array Dimension...
1

Our Array Shape...
(6,)

Result...
[ 25 1000 625 27000 1600 125000]

更新於:2022年2月7日

570 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告