numpy字符串操作 |索引()函数
numpy.core.defchararray.index(arr, sub, start=0, end=None)
是另一个在 numpy 中进行字符串操作的函数。它返回字符串中为arr中的每个元素找到子字符串 sub 的最低索引。如果 sub 不包含在[start, end]
范围内,则返回值错误。
Parameters:
arr : array_like of str or unicode.
sub : [str or unicode] The substring which to be searched.
start : [ int, optional] The starting location in each string.
end : [ int, optional] The ending location in each string.
Returns : [ndarray] Output array of int.
代码#1:
# Python program explaining
# numpy.char.index() method
# importing numpy
import numpy as geek
# input arrays
in_arr = geek.array(['aAaAaA', 'baA', 'abBABba'])
print ("Input array : ", in_arr)
# output arrays
out_arr = geek.char.index(in_arr, sub ='a')
print ("Output array: ", out_arr)
输出:
Input array : ['aAaAaA' 'baA' 'abBABba']
Output array: [0 1 0]
代码#2:
# Python program explaining
# numpy.char.index() method
# importing numpy
import numpy as geek
# input arrays
in_arr = geek.array(['aAaAaA', 'aA', 'abBABba'])
print ("Input array : ", in_arr)
# output arrays
out_arr = geek.char.index(in_arr, sub ='A', start = 1, end = 4)
print ("Output array: ", out_arr)
输出:
Input array : ['aAaAaA' 'aA' 'abBABba']
Output array: [1 1 3]
代码 #3:如果未找到子字符串,则引发 ValueError。
# Python program explaining
# numpy.char.index() method
# importing numpy
import numpy as geek
# input arrays
in_arr = geek.array(['aAaAaA', 'aA', 'abBABba'])
print ("Input array : ", in_arr)
# output arrays
out_arr = geek.char.index(in_arr, sub ='A', start = 3, end = 7)
print ("Output array: ", out_arr)
输出:
ValueError: substring not found