在 Numpy 中返回左侧填充零的数字字符串
numpyserver side programmingprogramming更新于 2025/9/24 4:52:17
要返回左侧填充零的数字字符串,请使用 Python Numpy 中的 numpy.char.zfill() 方法。此处:
第一个参数是输入/输出数组
第二个参数是"宽度",即数组左侧填充元素的字符串宽度
numpy.char 模块为 numpy.str_ 或 numpy.bytes_ 类型的数组提供了一组矢量化字符串操作。
步骤
首先,导入所需的库 −
import numpy as np
创建一个一维字符串数组 −
arr = np.array(['Tom', 'John', 'Kate', 'Amy', 'Brad'])
显示我们的数组 −
print("数组...
",arr)
获取数据类型 −
print("
数组数据类型...
",arr.dtype)
获取数组的维度 −
print("
数组维度...
",arr.ndim)
获取数组的形状 −
print("
我们的数组形状...
",arr.shape)
获取数组元素的数量 −
print("
数组中的元素...
",arr.size)
要返回左侧填充零的数字字符串,请使用 numpy.char.zfill() 方法 −
print("
结果...
",np.char.zfill(arr, width = 15))
示例
import numpy as np
# 创建一个一维字符串数组
arr = np.array(['Tom', 'John', 'Kate', 'Amy', 'Brad'])
# 显示我们的数组
print("数组...
",arr)
# 获取数据类型
print("
数组数据类型...
",arr.dtype)
# 获取数组的维度
print("
数组维度...
",arr.ndim)
# 获取数组的形状
print("
我们的数组形状...
",arr.shape)
# 获取数组元素的数量
print("
数组中元素的数量...
",arr.size)
# 要返回左侧填充零的数字字符串,请使用 Python Numpy 中的 numpy.char.zfill() 方法
# 第一个参数是输入输出数组
# 第二个参数是"宽度",即用于在数组中左侧填充元素的字符串宽度
print("
结果...
",np.char.zfill(arr, width = 15))
输出
数组... ['Tom' 'John' 'Kate' 'Amy' 'Brad'] 数组数据类型... <U4 数组维度... 1 我们的数组形状... (5,) 数组中元素的数量... 5 结果... ['000000000000Tom' '00000000000John' '00000000000Kate' '000000000000Amy' '00000000000Brad']

