numpy数组的字符串表示形式,逗号分隔其元素 [英] string representation of a numpy array with commas separating its elements

查看:1274
本文介绍了numpy数组的字符串表示形式,逗号分隔其元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组,例如:

I have a numpy array, for example:

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

如果我将其打印或使用str()将其转换为字符串,我将得到:

if I print it or turn it into a string with str() I get:

print w_points
[[-468.927  -11.299   76.271 -536.723]
 [-429.379 -694.915 -214.689  745.763]
 [   0.       0.       0.       0.   ]]

我需要将其转换为一个字符串,并使用两个逗号分隔,同时保留2D数组结构,即:

I need to turn it into a string that prints with separating commas while keeping the 2D array structure, that is:

[[-468.927,  -11.299,   76.271, -536.723],
 [-429.379, -694.915, -214.689,  745.763],
 [   0.,       0.,       0.,       0.   ]]

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

Does anybody know an easy way of turning a numpy array to that form of string?

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

I know that .tolist() adds the commas but the result loses the 2D structure.

推荐答案

尝试使用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.   ]])

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

If you plan on using large numpy arrays, set np.set_printoptions(threshold=np.nan) first. Without it, the array representation will be truncated after about 1000 entries (by default).

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

当然,如果您有那么大的数组,那么它开始变得不那么有用了,您可能应该以其他方式分析数据,而不仅仅是查看数据,并且有

Of course, if you have arrays that large, this starts to become less useful and you should probably analyze the data some way other than just looking at it and there are better ways of persisting a numpy array than saving it's repr to a file...

这篇关于numpy数组的字符串表示形式,逗号分隔其元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆