2

I have a rather big numpy array of M*N ints and I want to end up with a M array of strings that have all N corresponding ints concatenated. I tried using a view but this is probably not the way to go with numpy.

1
  • 1
    Please shows some example input and the desired output. Commented Sep 20, 2014 at 14:30

3 Answers 3

1

Hope this is what you want

numpy.apply_along_axis(numpy.array_str,0,array)

Look the documentation of apply_along_axis

http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html

and array_str

http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_str.html

for deeper understanding

Sign up to request clarification or add additional context in comments.

2 Comments

The output of this looks fishy: np.apply_along_axis(np.array_str,1,np.arange(12).reshape(3,4)) => array(['[0 1 2 3]', '[4 5 6 7]', '[ 8 9 10'], dtype='|S9')
np.array([np.array_str(x) for x in X]) handles the variable length of the lines better.
1

if you want to concatenating ints to string it wasnt be numpy array longer ! you will have a list with string indexes.

this is an example that concatenate 'a' to a numpy zero array :

>>> np.zeros(10)
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

>>> [str(i)+'a' for i in np.zeros(10)]
['0.0a', '0.0a', '0.0a', '0.0a', '0.0a', '0.0a', '0.0a', '0.0a', '0.0a', '0.0a']
>>> 

Comments

1

Without an example, your request is unclear. But here's one way of understanding it

In [13]: X=np.arange(12).reshape(3,4)
In [14]: np.array([''.join([str(i) for i in x]) for x in X])
Out[14]: 
array(['0123', '4567', '891011'], 
    dtype='|S6')

I have a 3x4 array; I convert each element to a string using str(i), and use join to concatenate the strings of a row into one longer string.

That's not a very satisfying answer, especially when joining '9' to '10'. Of course it could be refined by elaborating on the 'int' to 'string' formatting (ie. fixed width), maybe adding delimiters in the 'join', etc.

In [21]: np.array([','.join(['{:*^8}'.format(i) for i in x]) for x in X])
Out[21]: 
array(['***0****,***1****,***2****,***3****',
       '***4****,***5****,***6****,***7****',
       '***8****,***9****,***10***,***11***'], 
      dtype='|S35')

A view would only work if what you want is some sort of string to bytes representation, or str to char.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.