返回一個布林陣列,其中陣列中的字串元素以給定的字首開頭,但在 Python 中測試開始和結束位置。


要返回一個布林陣列,其中在字串陣列元素以指定字首開頭的位置為 True,請在 Python NumPy 中使用 numpy.char.startswith() 方法。該方法輸出一個布林陣列。第一個引數是輸入陣列。第二個引數是字首。使用可選的 start 引數,從該位置開始測試。使用可選的 end 引數,在該位置停止比較。

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個字串的一維陣列 -

arr = np.array(['KATIE', 'JOHN', 'KATE', 'KmY', 'BRAD'])

顯示我們的陣列 -

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.startswith() 方法。該方法輸出一個布林陣列 -

print("\nResult (startswith)...\n",np.char.startswith(arr, 'K', start = 0, end = 2))

示例

import numpy as np

# Create a One-Dimensional array of strings
arr = np.array(['KATIE', 'JOHN', 'KATE', 'KmY', 'BRAD'])

# 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 begins with prefix, use the numpy.char.startswith() method in Python Numpy
# The method outputs an array of bools.
print("\nResult (startswith)...\n",np.char.startswith(arr, 'K', start = 0, end = 2))

輸出

Array...
['KATIE' 'JOHN' 'KATE' 'KmY' 'BRAD']

Array datatype...
<U5

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result (startswith)...
[ True False True True False]

更新於: 2022年2月24日

335 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.