返回 NumPy 中數字的符號的逐元素指示


要返回數字的符號的逐元素指示,請在 Python NumPy 中使用 **numpy.sign()** 方法。

如果 x < 0,則符號函式返回 -1;如果 x==0,則返回 0;如果 x > 0,則返回 1。對於 nan 輸入,返回 nan。對於複數輸入,如果 x.real != 0,則符號函式返回 sign(x.real) + 0j;否則返回 sign(x.imag) + 0j。

對於複數 nan 輸入,返回 complex(nan, 0)。在複數的常用符號定義中,不止一個。此處使用的定義等效於 x/x*x,這與常見的替代方案 x/|x| 不同。

步驟

首先,匯入所需的庫 -

import numpy as np

使用 array() 方法建立具有浮點型別的陣列 -

arr = np.array([50.8, 120.3, 200.7, -320.1, -450.4, 0])

顯示陣列 -

print("Array...
", arr)

獲取陣列的型別 -

print("
Our Array type...
", arr.dtype)

獲取陣列的維度 -

print("
Our Array Dimension...
",arr.ndim)

獲取陣列的形狀 -

print("
Our Array Shape...
",arr.shape)

要返回數字的符號的逐元素指示,請使用 numpy.sign() 方法 -

print("
Result...
",np.sign(arr))

示例

import numpy as np

# Create an array with float type using the array() method
arr = np.array([50.8, 120.3, 200.7, -320.1, -450.4, 0])

# 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) # To return an element-wise indication of the sign of a number, use the numpy.sign() method in Python Numpy print("
Result...
",np.sign(arr))

輸出

Array...
[ 50.8 120.3 200.7 -320.1 -450.4 0. ]

Our Array type...
float64

Our Array Dimension...
1

Our Array Shape...
(6,)

Result...
[ 1. 1. 1. -1. -1. 0.]

更新於: 2022年2月8日

214 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.