返回用 Numpy 中的零左填充的数字字符串
若要返回用零左填充的数字字符串,请在 Python Numpy 中使用 numpy.char.zfill() 方法。其中:
第 1 个参数是输入数组
第 2 个参数是“宽度”,即数组中元素的左填充字符串的宽度
numpy.char 模块提供了一组针对类型为 numpy.str_ 或 numpy.bytes_ 的数组的向量化字符串操作。
步骤
首先,导入所需的库 −
import numpy as np
创建一个字符串的一维数组 −
arr = np.array(['Tom', 'John', 'Kate', 'Amy', 'Brad'])
显示数组 −
print("Array...
",arr)获取数据类型 −
print("
Array datatype...
",arr.dtype)
获取数组的维度 −
print("
Array Dimensions...
",arr.ndim)获取数组的形状 −
print("
Our Array Shape...
",arr.shape)
获取数组的元素个数 −
print("
Elements in the Array...
",arr.size)若要返回用零左填充的数字字符串,请使用 numpy.char.zfill() 方法 −
print("
Result...
",np.char.zfill(arr, width = 15))
范例
import numpy as np
# Create a One-Dimensional array of string
arr = np.array(['Tom', 'John', 'Kate', 'Amy', 'Brad'])
# Displaying our array
print("Array...
",arr)
# Get the datatype
print("
Array datatype...
",arr.dtype)
# Get the dimensions of the Array
print("
Array Dimensions...
",arr.ndim)
# Get the shape of the Array
print("
Our Array Shape...
",arr.shape)
# Get the number of elements of the Array
print("
Number of elements in the Array...
",arr.size)
# To return the numeric string left-filled with zeros, use the numpy.char.zfill() method in Python Numpy
# The 1st parameter is the inout array
# The 2nd parameter is the "width" i.e the width of string to leftfill elements in array
print("
Result...
",np.char.zfill(arr, width = 15))输出
Array... ['Tom' 'John' 'Kate' 'Amy' 'Brad'] Array datatype... <U4 Array Dimensions... 1 Our Array Shape... (5,) Number of elements in the Array... 5 Result... ['000000000000Tom' '00000000000John' '00000000000Kate' '000000000000Amy' '00000000000Brad']
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP