NumPy 有几个对字符串数组有用的函数。见NumPy docs on String operations。您正在寻找的功能是np.core.defchararray.zfill 或其alias np.char.zfill。
以David Buck's answer 中的数组为例:
>>> import numpy as np
>>> arr = np.array([[['3', '6', '12'],
['0', '1', '3'],
['5', 'T', '8'],
['19', '15', '11']],
[['6', '3', '1'],
['10', '10', 'QR'],
['7', '11', '9'],
['12', '13', '11']],
[['1', 'G', '3'],
['10', '9', '2'],
['18', '12', '17'],
['6', '1', '10']]])
>>> np.char.zfill(arr, 2)
array([[['03', '06', '12'],
['00', '01', '03'],
['05', '0T', '08'],
['19', '15', '11']],
[['06', '03', '01'],
['10', '10', 'QR'],
['07', '11', '09'],
['12', '13', '11']],
[['01', '0G', '03'],
['10', '09', '02'],
['18', '12', '17'],
['06', '01', '10']]], dtype='<U2')
如果你想避免给非数字元素添加零,我们可以使用boolean array indexing和np.core.defchararray.isdigit函数或其别名np.char.isdigit:
>>> mask = np.char.isdigit(arr)
>>> mask
array([[[ True, True, True],
[ True, True, True],
[ True, False, True],
[ True, True, True]],
[[ True, True, True],
[ True, True, False],
[ True, True, True],
[ True, True, True]],
[[ True, False, True],
[ True, True, True],
[ True, True, True],
[ True, True, True]]])
>>> arr[mask] = np.char.zfill(arr[mask], 2)
>>> arr
array([[['03', '06', '12'],
['00', '01', '03'],
['05', 'T', '08'],
['19', '15', '11']],
[['06', '03', '01'],
['10', '10', 'QR'],
['07', '11', '09'],
['12', '13', '11']],
[['01', 'G', '03'],
['10', '09', '02'],
['18', '12', '17'],
['06', '01', '10']]], dtype='<U2')