返回一個布林陣列,其中陣列中字串元素以Python中的字尾結尾的地方為True
要在Python NumPy中返回一個布林陣列,其中陣列中字串元素以後綴結尾的地方為True,可以使用numpy.char.endswith()方法。第一個引數是輸入陣列。第二個引數是字尾。numpy.char模組為numpy.str_型別的陣列提供了一組向量化的字串操作。
步驟
首先,匯入所需的庫:
import numpy as np
建立一個一維字串陣列:
arr = np.array(['KATIE', 'JOHN', 'KATE', 'AmY', 'BRADley'])
顯示我們的陣列:
print("Array...\n",arr)
獲取資料型別:
print("\nArray datatype...\n",arr.dtype)
獲取陣列的維度:
print("\nArray Dimensions...\n",arr.ndim)
獲取陣列的形狀:
print("\nOur Array Shape...\n",arr.shape)
獲取陣列的元素個數:
print("\nNumber of elements in the Array...\n",arr.size)
要返回一個布林陣列,其中陣列中字串元素以後綴結尾的地方為True,可以使用numpy.char.endswith()方法:
print("\nResult (endswith)...\n",np.char.endswith(arr, 'E'))
示例
import numpy as np # Create a One-Dimensional array of strings arr = np.array(['KATIE', 'JOHN', 'KATE', 'AmY', 'BRADley']) # Displaying our array print("Array...\n",arr) # Get the datatype print("\nArray datatype...\n",arr.dtype) # Get the dimensions of the Array print("\nArray Dimensions...\n",arr.ndim) # Get the shape of the Array print("\nOur Array Shape...\n",arr.shape) # Get the number of elements of the Array print("\nNumber of elements in the Array...\n",arr.size) # To return a boolean array which is True where the string element in array ends with suffix, use the numpy.char.endswith() method in Python Numpy # The first parameter is the input array # The second parameter is the suffix print("\nResult (endswith)...\n",np.char.endswith(arr, 'E'))
輸出
Array... ['KATIE' 'JOHN' 'KATE' 'AmY' 'BRADley'] Array datatype... <U7 Array Dimensions... 1 Our Array Shape... (5,) Number of elements in the Array... 5 Result (endswith)... [ True False True False False]
廣告