Home > Enterprise >  Setting integers inside array to a fixed length
Setting integers inside array to a fixed length

Time:07-06

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?

CodePudding user response:

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.

CodePudding user response:

You could try this: 'd'3

CodePudding user response:

You first need to change the type of your array:

dummy_array = dummy_array.astype(str)

And then you can pad your strings:

for i in range(len(dummy_array)):
    dummy_array[i] = dummy_array[i].rjust(6)

Result:

>>> dummy_array
array(['  1234', '653932', ' 21394', ' 99999', '  1289'])

CodePudding user response:

'{0:06d}'.format(x) returns a formatted str for a passed int already.

The numpy array's dtype was set to int64 on instantiation, by automatically guessing the array type from passed values of the python list with [1234, 653932, 21394, 99999, 1289].

As your code modifies the original array, it converts values back to int64 when you pass a str to it.

You can ofc. set the overall type to object as in @Lucas D. Meier 's answer.

But you can also create a new numpy array of str from this transformation

dummy_array = np.array([1234, 653932, 21394, 99999, 1289])
res_array = np.array(['{0:06d}'.format(x) for x in dummy_array])
=> array(['001234', '653932', '021394', '099999', '001289'], dtype='<U6')

  • Related