将二维 numpy 数组转换为一维字符串

Converting a 2D numpy array to a 1D string

我有一个像这样的 numpy 数组 - arr = np.array([[1, 2, 3], [2, 3, 4], [5, 6, 7]])

我希望能够像这样将它转换为字符串表示形式 - out = np.array(['1 2 3', '2 3 4', '5 6 7'])

下面的方法有效,但对于大型数组来说它可能不是最有效的 -

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)

有更快的方法吗?

您可以使用 list comprehension:

out = np.array([str(l).strip("[]") for l in arr])
#array(['1 2 3', '2 3 4', '5 6 7'], dtype='<U5')