返回一个布尔数组,其中数组中的字符串元素以给定的后缀结尾,但在 Python 中测试开头和结尾
要返回一个布尔数组,其中在数组中的字符串元素以后缀结尾的地方为 True,请在 Python Numpy 中使用 numpy.char.endswith() 方法。该方法输出一个布尔数组。第一个参数是输入数组。第二个参数是后缀。使用可选的 start 参数,从该位置开始测试。使用可选的 end 参数,在该位置停止比较。
步骤
首先,导入所需的库 -
import numpy as np
创建一个字符串的一维数组 -
arr = np.array(['KATIE', 'JOHN', 'KATE', 'AmY', 'CRADlE'])
显示我们的数组 -
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', start = 2, end = 4))
示例
import numpy as np
# Create a One-Dimensional array of strings
arr = np.array(['KATIE', 'JOHN', 'KATE', 'AmY', 'CRADlE'])
# 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 method outputs an array of bools.
print("\nResult (endswith)...\n",np.char.endswith(arr, 'E', start = 2, end = 4))输出
Array... ['KATIE' 'JOHN' 'KATE' 'AmY' 'CRADlE'] Array datatype... <U6 Array Dimensions... 1 Our Array Shape... (5,) Number of elements in the Array... 5 Result (endswith)... [False False True False False]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP