返回 Python 中陣列輸入的逐元素平方


要返回陣列輸入的逐元素平方,請在 Python 中使用 numpy.square() 方法。該方法返回與 x 形狀和資料型別相同的逐元素 x*x。如果 x 是標量,則這是一個標量。

第一個引數 x 是輸入資料。第二個引數 out 是儲存結果的位置。如果提供,則其形狀必須與輸入廣播到的形狀相同。如果未提供或為 None,則返回一個新分配的陣列。元組(只能作為關鍵字引數)的長度必須等於輸出的數量。

第三個引數 where,此條件將廣播到輸入上。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他位置,out 陣列將保留其原始值。請注意,如果透過預設 out=None 建立未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化狀態。

步驟

首先,匯入所需的庫:

import numpy as np

使用 array() 方法建立一個 numpy 陣列。我們添加了 int 型別的元素:

arr = np.array([[25, -50, 75], [-90, 81, 64]])

顯示陣列:

print("Our Array...\n",arr)

檢查維度:

print("\nDimensions of our Array...\n",arr.ndim)

獲取資料型別:

print("\nDatatype of our Array object...\n",arr.dtype)

要返回陣列輸入的逐元素平方,請使用 numpy.square() 方法。該方法返回與 x 形狀和資料型別相同的逐元素 x*x。如果 x 是標量,則這是一個標量:

print("\nResult...\n",np.square(arr))

示例

import numpy as np

# Creating a numpy array using the array() method
# We have added elements of int type
arr = np.array([[25, -50, 75], [-90, 81, 64]])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# To return the element-wise square of the array input, use the numpy.square() method in Python
# The method returns the element-wise x*x, of the same shape and dtype as x. This is a scalar if x is a scalar.
print("\nResult...\n",np.square(arr))

輸出

Our Array...
[[ 25 -50 75]
[-90 81 64]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

Result...
[[ 625 2500 5625]
[8100 6561 4096]]

更新於:2022年2月25日

5K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.