在 Python 中返回一個包含子字串非重疊出現次數的陣列
要返回一個包含子字串非重疊出現次數的陣列,請在 Python Numpy 中使用 numpy.char.count() 方法。第一個引數是 sub,即要搜尋的子字串。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)要返回一個包含子字串非重疊出現次數的陣列,請在 Python Nump 中使用 numpy.char.count() 方法。第一個引數是 sub,即要搜尋的子字串 -
print("\nResult (count)...\n",np.char.count(arr, 'A'))
示例
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 an array with the number of non-overlapping occurrences of substring, use the numpy.char.count() method in Python Numpy
# The first parameter is the sub i.e. the substring to search for
print("\nResult (count)...\n",np.char.count(arr, 'A'))輸出
Array... ['kATIE' 'JOHN' 'KAte' 'AmY' 'BRADley'] Array datatype... <U7 Array Dimensions... 1 Our Array Shape... (5,) Number of elements in the Array... 5 Result (count)... [1 0 1 1 1]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP