返回一个布尔数组,其中元素以指定后缀结尾,使用Python中的numpy.char.endswith()方法

返回一个布尔数组,其中元素以指定后缀结尾,使用Python中的numpy.char.endswith()方法

要返回一个布尔数组,其中元素以指定后缀结尾,请在Python的Numpy中使用numpy.char.endswith()方法。第一个参数是输入数组,第二个参数是后缀。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)

通过使用numpy.char.endswith()方法,可以返回一个布尔数组,其中字符串数组中的元素以suffix结尾,返回为True。

print("\nResult (endswith)...\n",np.char.endswith(arr, 'E'))

示例

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 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 first parameter is the input array
# The second parameter is the suffix
print("\nResult (endswith)...\n",np.char.endswith(arr, 'E'))

输出

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

Array datatype...
<U7

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程