在 Python 中,對於每個元素,返回字串中找到子字串的最低索引


要在 Python Numpy 中返回字串中找到子字串 sub 的最低索引,請使用 numpy.char.find() 方法。該方法返回整數輸出陣列。如果未找到 sub,則返回 -1。第一個引數是輸入陣列。第二個引數是要搜尋的子字串。

步驟

首先,匯入所需的庫 -

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)

要返回字串中找到子字串 sub 的最低索引,請使用 numpy.char.find() 方法 -

print("\nResult (find)...\n",np.char.find(arr, 'AT'))

示例

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 the lowest index in the string where substring sub is found, use the numpy.char.find() method in Python Numpy
# The method returns the output array of ints. Returns -1 if sub is not found.
# The first parameter is the input array
# The second parameter is the substring to be searched
print("\nResult (find)...\n",np.char.find(arr, 'AT'))

輸出

Array...
['KATIE' 'JOHN' 'KATE' 'AmY' 'BRADley']

Array datatype...
<U7

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result (find)...
[ 1 -1 1 -1 -1]

更新於: 2022年2月24日

97 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.