使用 NumPy 中的比較運算子對兩個字串陣列進行逐元素比較
要使用比較運算子對兩個字串陣列進行逐元素比較,請在 Python NumPy 中使用 **numpy.compare_chararrays()** 方法。arr1 和 arr2 是要比較的形狀相同的兩個輸入字串陣列。第三個引數是 rstrip,如果為 True,則在比較之前會刪除字串末尾的空格。
NumPy 提供全面的數學函式、隨機數生成器、線性代數例程、傅立葉變換等等。它支援各種硬體和計算平臺,並且與分散式、GPU 和稀疏陣列庫相容良好。
步驟
首先,匯入所需的庫:
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)
要使用比較運算子對兩個字串陣列進行逐元素比較,請使用 numpy.compare_chararrays() 方法。arr1 和 arr2 是要比較的形狀相同的兩個輸入字串陣列。第三個引數是 rstrip,如果為 True,則在比較之前會刪除字串末尾的空格:
print("
Result...
",np.compare_chararrays(arr1, arr2, ">", rstrip = True))
示例
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 perform element-wise comparison of two string arrays using a comparison operator, use the numpy.compare_chararrays() method in Python Numpy # The arr1 and arr2 are the two input string arrays of the same shape to be compared # The 3rd parameter is rstrip , if True, the spaces at the end of Strings are removed before the comparison. print("
Result...
",np.compare_chararrays(arr1, arr2, ">", rstrip = True))
輸出
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 False True False True False True]
廣告