Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

python - string representation of a numpy array with commas separating its elements

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.   ]])

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.   ]]

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.   ]]

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using 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.   ]])

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...