在 Python 中返回一个布尔数组,其中数组中的字符串元素以指定的前缀开头。
要返回一个布尔数组,其中数组中的字符串元素以指定的前缀开头,请在 Python Numpy 中使用 numpy.char.startswith() 方法。第一个参数是输入数组。第二个参数是前缀。
步骤
首先,导入所需的库 -
import numpy as np
创建一个一维字符串数组 -
arr = np.array(['KATIE', 'JOHN', 'KATE', 'KmY', 'BRAD'])
显示我们的数组 -
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.startswith() 方法 -
print("\nResult (startswith)...\n",np.char.startswith(arr, 'K'))
示例
import numpy as np
# Create a One-Dimensional array of strings
arr = np.array(['KATIE', 'JOHN', 'KATE', 'KmY', 'BRAD'])
# 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 starts with prefix, use the numpy.char.startswith() method in Python Numpy
# The first parameter is the input array
# The second parameter is the prefix
print("\nResult (startswith)...\n",np.char.startswith(arr, 'K'))输出
Array... ['KATIE' 'JOHN' 'KATE' 'KmY' 'BRAD'] Array datatype... <U5 Array Dimensions... 1 Our Array Shape... (5,) Number of elements in the Array... 5 Result (startswith)... [ True False True True False]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP