numpy字符串操作 | zfill()函数
numpy.core.defchararray.zfill(arr, width)
是另一个在 numpy 中进行字符串操作的函数。对于数组中的每个元素,它返回左填充零的数字字符串。左填充零的数量根据宽度发生。
Parameters:
arr : array_like of str or unicode.Input array.
width : [int] The final width of the string after filling zeros.
Returns : [ndarray] Output array of str or unicode, depending on input type.
代码#1:
# Python program explaining
# numpy.char.zfill() method
# importing numpy
import numpy as geek
# input array
in_arr = geek.array(['Geeks', 'for', 'Geeks'])
print ("Input array : ", in_arr)
# setting the width of each string to 8
width = 8
# output array
out_arr = geek.char.zfill(in_arr, width)
print ("Output array: ", out_arr)
输出:
Input array : ['Geeks' 'for' 'Geeks']
Output array: ['000Geeks' '00000for' '000Geeks']
代码#2:
# Python program explaining
# numpy.char.zfill() method
# importing numpy
import numpy as geek
# input array
in_arr = geek.array(['1', '11', '111'])
print ("Input array : ", in_arr)
# setting the width of each string to 5
width = 5
# output array
out_arr = geek.char.zfill(in_arr, width)
print ("Output array: ", out_arr)
输出:
Input array : ['1' '11' '111']
Output array: ['00001' '00011' '00111']