D
D
deeppsycoder2020-10-16 23:47:15
numpy
deeppsycoder, 2020-10-16 23:47:15

How can I set the string dtype when using the apply_along_axis method, or is it better to represent an array as a string?

You need to represent the array as a string with the given element separators. Came across such behavior of the following code.

>>> def array_to_string(array, sep):
>>>     return f'{sep}'.join(map(str, array))
>>>
>>>
>>> a = np.arange(12).reshape((3, 4))
>>> np.apply_along_axis(array_to_string, 1, a, ',')

array(['0,1,2,3', '4,5,6,7', '8,9,10,'], dtype='<U7')

>>> a = np.arange(16).reshape((4, 4))
>>> np.apply_along_axis(array_to_string, 1, a, ',')

array(['0,1,2,3', '4,5,6,7', '8,9,10,', '12,13,1'], dtype='<U7')

>>> a = np.arange(9).reshape((3, 3))
>>> np.apply_along_axis(array_to_string, 1, a, ',')

array(['0,1,2', '3,4,5', '6,7,8'], dtype='<U5')


That is, the length of the string is set after processing the first vector, and if the subsequent ones are longer, then they are cut off. Is it possible to set the desired result type?

On the other hand, using apply_along_axis for this purpose is not the best idea. There is an array2string function with a separator parameter , although it still won't allow, say, to separate elements with a comma, and strings with a semicolon.

So far, the most successful solution to my problem, in my opinion, is to use the tolist method and then convert the list to a string, which can easily be converted back to a list using the eval function and then to an array (which is what I eventually need).

In general, the problem is solved, but the question remains.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question