简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM