0

I have a numpy array that looks like this - arr = np.array([[1, 2, 3], [2, 3, 4], [5, 6, 7]]).

I want to be able to convert it to a string representation like so - out = np.array(['1 2 3', '2 3 4', '5 6 7']).

The following works, but it's probably not the most efficient for large arrays -

import numpy as np

arr = np.array([[1, 2, 3], [2, 3, 4], [5, 6, 7]])

out = np.apply_along_axis(
    lambda s: np.array2string(s, separator=" ", formatter={'int': lambda x: str(x)})[1:-1],
    axis=1, arr=arr
)

print(out)

Is there a faster way of doing this?

4
  • A simple list comprehension like : [" ".join(map(str, i)) for i in arr]? Commented Feb 25, 2021 at 7:00
  • why are you doing this? It is an unusual operation, and there may be a better way of doing what you want Commented Feb 25, 2021 at 7:07
  • A list comprehension will be faster than apply... Commented Feb 25, 2021 at 7:14
  • I didn't know list comprehension was going to be faster here. Thanks! @anon01 I agree this is probably not the best way of doing this but we need to do this conversion due to reasons relating relying on BigQuery and the format in which is gives out data. Commented Feb 25, 2021 at 10:23

1 Answer 1

1

You can use list comprehension:

out = np.array([str(l).strip("[]") for l in arr])
#array(['1 2 3', '2 3 4', '5 6 7'], dtype='<U5')
Sign up to request clarification or add additional context in comments.

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.