按元素返回 Python 中字符串数组的长度


若想按元素返回字符串数组的长度,请在 Python Numpy 中使用 numpy.char.str_len() 方法。该方法将返回一个整数输出数组。

步骤

首先,导入所需的库 −

import numpy as np

创建一个一维字符串数组 −

arr = np.array(['Amy', 'Scarlett', 'Katie', 'Brad', 'Tom'])

显示此数组 −

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.str_len() 方法 −

print("\nResult (length element-wise)...\n",np.char.str_len(arr))

示例

import numpy as np

# Create a One-Dimensional array of strings
arr = np.array(['Amy', 'Scarlett', 'Katie', 'Brad', 'Tom'])

# 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 the length of a string array element-wise, use the numpy.char.str_len() method in Python Numpy
# The method returns an output array of integers.

print("\nResult (length element-wise)...\n",np.char.str_len(arr))

输出

Array...
['Amy' 'Scarlett' 'Katie' 'Brad' 'Tom']

Array datatype...
<U8

Array Dimensions...
1

Our Array Shape...
(5,)

Number of elements in the Array...
5

Result (length element-wise)...
[3 8 5 4 3]

更新于: 24-02-2022

1K+ 浏览次数

开启你的职业生涯

完成课程以获得认证

开始
Advertisement
© . All rights reserved.