Skip to content
Advertisement

Setting integers inside array to a fixed length

I´m trying to generate an array with integers of a fixed length of 6, so that e.g. 1234 is displayed as 001234 and 12345 as 012345. I can get it to work for an integer using:

x = 12345
x = '{0:06d}'.format(x)
print(x)
>>> 012345

I tried the same method for an array, but it doesn`t seem to work, so how can I convert this method to array entries?

dummy_array = np.array([1234, 653932, 21394, 99999, 1289])
for i in range(len(dummy_array)
    dummy_array[i] = '{0:06d}'.format(dummy[i])

print(dummy_array[2]) #test
>>>21394

Do I need convert the array entries to strings first?

Advertisement

Answer

If you set:

dummy_array = np.array([1234, 653932, 21394, 99999, 1289],dtype=object)

it allows the numpy array to contain integers and strings simultaneously, which was your problem. With this simple dtype argument your code will work.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement