numpy数组的字符串表示形式,用逗号分隔其元素

mar*_*ako 28 python numpy

我有一个numpy数组,例如:

points = np.array([[-468.927,  -11.299,   76.271, -536.723],
                   [-429.379, -694.915, -214.689,  745.763],
                   [   0.,       0.,       0.,       0.   ]])
Run Code Online (Sandbox Code Playgroud)

如果我打印它或用str()把它变成一个字符串我得到:

print w_points
[[-468.927  -11.299   76.271 -536.723]
 [-429.379 -694.915 -214.689  745.763]
 [   0.       0.       0.       0.   ]]
Run Code Online (Sandbox Code Playgroud)

我需要把它变成一个字符串,用逗号分隔打印,同时保持2D数组结构,即:

[[-468.927,  -11.299,   76.271, -536.723],
 [-429.379, -694.915, -214.689,  745.763],
 [   0.,       0.,       0.,       0.   ]]
Run Code Online (Sandbox Code Playgroud)

有没有人知道将numpy数组转换为字符串形式的简单方法?

我知道.tolist()会添加逗号,但结果会丢失2D结构.

mgi*_*son 52

尝试使用 repr

>>> import numpy as np
>>> points = np.array([[-468.927,  -11.299,   76.271, -536.723],
...                    [-429.379, -694.915, -214.689,  745.763],
...                    [   0.,       0.,       0.,       0.   ]])
>>> print repr(points)
array([[-468.927,  -11.299,   76.271, -536.723],
       [-429.379, -694.915, -214.689,  745.763],
       [   0.   ,    0.   ,    0.   ,    0.   ]])
Run Code Online (Sandbox Code Playgroud)

如果您打算使用大型numpy数组,np.set_printoptions(threshold=np.nan)请先设置.没有它,数组表示将在大约1000个条目之后被截断(默认情况下).

>>> arr = np.arange(1001)
>>> print repr(arr)
array([   0,    1,    2, ...,  998,  999, 1000])
Run Code Online (Sandbox Code Playgroud)

当然,如果你有大的数组,这开始变得不那么有用了你应该以某种方式分析数据,而不仅仅是看它,并且有更好的方法来持久化numpy数组而不是将它保存repr到文件中...


K.K*_*Kit 18

现在,在numpy 1.11中,有numpy.array2string:

In [279]: a = np.reshape(np.arange(25, dtype='int8'), (5, 5))

In [280]: print(np.array2string(a, separator=', '))
[[ 0,  1,  2,  3,  4],
 [ 5,  6,  7,  8,  9],
 [10, 11, 12, 13, 14],
 [15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24]]
Run Code Online (Sandbox Code Playgroud)

repr@mgilson 比较(显示"array()"和dtype):

In [281]: print(repr(a))
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]], dtype=int8)
Run Code Online (Sandbox Code Playgroud)

PS仍然需要np.set_printoptions(threshold=np.nan)大阵列.


var*_*wal 5

您正在寻找的功能是np.set_string_function. 来源

这个函数的作用是让你覆盖numpy 对象的默认值__str__或函数。__repr__如果将该repr标志设置为 True,该__repr__函数将被您的自定义函数覆盖。同样,如果您设置repr=False,该__str__函数将被覆盖。由于print调用了__str__对象的函数,所以我们需要设置repr=False.

例如:

np.set_string_function(lambda x: repr(x), repr=False)
x = np.arange(5)
print(x)
Run Code Online (Sandbox Code Playgroud)

将打印输出

array([0, 1, 2, 3, 4])
Run Code Online (Sandbox Code Playgroud)

更美观的版本是

array([0, 1, 2, 3, 4])
Run Code Online (Sandbox Code Playgroud)

这使

[[1., 0., 0.],
 [0., 1., 0.],
 [0., 0., 1.]]
Run Code Online (Sandbox Code Playgroud)

希望这能回答您的问题。