Ananda
Ananda

Reputation: 3270

Converting a 2D numpy array to a 1D string

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?

Upvotes: 0

Views: 706

Answers (1)

Pablo C
Pablo C

Reputation: 4761

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')

Upvotes: 1

Related Questions