比較兩個字串陣列是否相等並在 NumPy 中返回 True
要比較兩個字串陣列是否相等並返回 True,請在 Python NumPy 中使用 **numpy.char.equal()** 方法。arr1 和 arr2 是兩個相同形狀的輸入字串陣列。與 numpy.equal 不同,此比較是透過首先從字串末尾去除空格字元來執行的。此行為是為了與 numarray 保持向後相容性。
numpy.char 模組為型別為 numpy.str_ 或 numpy.bytes_ 的陣列提供了一組向量化字串操作。
步驟
首先,匯入所需的庫 -
import numpy as np
建立兩個字串的一維陣列 -
arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad']) arr2 = np.array(['Cio', 'Tom', 'Cena', 'Kate', 'Adams', 'brad'])
顯示陣列 -
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.equal() 方法。arr1 和 arr2 是兩個相同形狀的輸入字串陣列 -
print("
Result...
",np.char.equal(arr1,arr2))
示例
import numpy as np
# Create two One-Dimensional arrays of string
arr1 = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])
arr2 = np.array(['Cio', 'Tom', 'Cena', 'Kate', 'Adams', 'brad'])
# 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 two string arrays are equal, use the numpy.char.equal() method in Python Numpy
# The arr1 and arr2 are the two input string arrays of the same shape.
print("
Result...
",np.char.equal(arr1,arr2))輸出
Array 1... ['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad'] Array 2... ['Cio' 'Tom' 'Cena' 'Kate' 'Adams' 'brad'] Our Array 1 type... <U5 Our Array 2 type... <U5 Our Array 1 Dimensions... 1 Our Array 2 Dimensions... 1 Our Array 1 Shape... (6,) Our Array 2 Shape... (6,) Result... [False True False True False False]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP