比較兩個NumPy陣列,如果第一個陣列大於等於第二個陣列,則返回True


要比較兩個陣列,如果第一個陣列大於等於第二個陣列,則返回True,可以使用Python NumPy中的**numpy.char.greater_equal()**方法。arr1和arr2是兩個形狀相同的輸入字串陣列。

與numpy.greater_equal不同,此比較是在首先去除字串末尾的空格字元後執行的。此行為是為了與numarray向後相容。

numpy.char模組為numpy.str_或numpy.bytes_型別的陣列提供了一組向量化字串操作。

步驟

首先,匯入所需的庫:

import numpy as np

建立兩個一維字串陣列:

arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad', 'aaa'])
arr2 = np.array(['Cio', 'Tom', 'Cena', 'Kate', 'Adams', 'brad', 'aa'])

顯示陣列:

print("Array 1...
", arr1) print("
Array 2...
", arr2)

獲取陣列的型別:

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

獲取陣列的維度:

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

獲取陣列的形狀:

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

要比較兩個陣列,如果第一個陣列大於等於第二個陣列,則返回True,可以使用numpy.char.greater_equal()方法。arr1和arr2是兩個形狀相同的輸入字串陣列:

print("
Result...
",np.char.greater_equal(arr1,arr2))

示例

import numpy as np

# Create two One-Dimensional arrays of string
arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad', 'aaa'])
arr2 = np.array(['Cio', 'Tom', 'Cena', 'Kate', 'Adams', 'brad', 'aa'])

# Display the arrays
print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To compare and return True if an array is greater than equal to another, use the numpy.char.greater_equal() method in Python Numpy # The arr1 and arr2 are the two input string arrays of the same shape. print("
Result...
",np.char.greater_equal(arr1,arr2))

輸出

Array 1...
['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad' 'aaa']

Array 2...
['Cio' 'Tom' 'Cena' 'Kate' 'Adams' 'brad' 'aa']

Our Array 1 type...
<U5

Our Array 2 type...
<U5

Our Array 1 Dimensions...
1

Our Array 2 Dimensions...
1

Our Array 1 Shape...
(7,)

Our Array 2 Shape...
(7,)

Result...
[False True True True True False True]

更新於:2022年2月18日

476 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

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