在 Numpy 中返回一个数组的副本,其元素以长度为 width 的字符串为中心
numpyserver side programmingprogramming更新于 2025/9/2 0:07:17
要返回一个数组的副本,其元素以长度为 width 的字符串为中心,请使用 Python Numpy 中的 numpy.char.center() 方法。width 是结果字符串的长度。该函数返回 str 或 unicode 格式的输出数组,具体取决于输入类型。
numpy.char 模块为 numpy.str_ 或 numpy.bytes_ 类型的数组提供了一组矢量化字符串操作。
步骤
首先,导入所需的库 −
import numpy as np
创建一个一维字符串数组 −
arr = np.array(['bella', 'toM', 'john', 'katE', 'amy', 'brad'])
显示我们的数组 −
print("数组...
",arr)
获取数据类型 −
print("
数组数据类型...
",arr.dtype)
获取数组的维度 −
print("
数组维度...
",arr.ndim)
获取数组的形状 −
print("
我们的数组形状...
",arr.shape)
获取数组元素的数量 −
print("
数组中的元素...
",arr.size)
To return a copy of an array with its elements centered in a string of length width, use the numpy.char.center() method. The width is the length of the resulting strings −
print("
结果...
",np.char.center(arr, width = 8))
示例
import numpy as np
# Create a One-Dimensional array of string
arr = np.array(['bella', 'toM', 'john', 'katE', 'amy', 'brad'])
# Displaying our array
print("数组...
",arr)
# Get the datatype
print("
数组数据类型...
",arr.dtype)
# 获取数组的维度
print("
数组维度...
",arr.ndim)
# 获取数组的形状
print("
我们的数组形状...
",arr.shape)
# 获取数组元素的数量
print("
数组中的元素...
",arr.size)
# To return a copy of an array with its elements centered in a string of length width, use the numpy.char.center() method in Python Numpy
# The width is the length of the resulting strings
print("
结果...
",np.char.center(arr, width = 8))
输出
数组... ['bella' 'toM' 'john' 'katE' 'amy' 'brad'] 数组数据类型... <U5 数组维度... 1 我们的数组形状... (6,) 数组中的元素... 6 结果... [' bella ' ' toM ' ' john ' ' katE ' ' amy ' ' brad ']

