Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print `numpy.ndarray` on a single line

While using scipy/numpy, I do get information that I store into a numpy.ndarray

>>> a
array([[ 0.15555605,  0.51031528,  0.84580176,  0.06722675],
       [ 0.60556045,  0.62721023, -0.48979983, -0.04152777],
       [-0.78044785,  0.58837543, -0.21146041, -0.13568023],
       [ 0.        ,  0.        ,  0.        ,  1.        ]])
>>> print(a)
[[ 0.15555605  0.51031528  0.84580176  0.06722675]
 [ 0.60556045  0.62721023 -0.48979983 -0.04152777]
 [-0.78044785  0.58837543 -0.21146041 -0.13568023]
 [ 0.          0.          0.          1.        ]]

How can I print the result on a single line?

I already checked:

>>> numpy.get_printoptions()
{'precision': 8, 'threshold': 1000, 'edgeitems': 3, 'linewidth': 75, 'suppress': False, 'nanstr': 'nan', 'infstr': 'inf', 'formatter': None}

But even setting linewidth to 1000 does no change this. Is there a way to change the displayed format of that type?

Is it also possible to add comma in between each number (like the array display but without the surrounding array(...))?

like image 815
M'vy Avatar asked May 23 '17 15:05

M'vy


People also ask

How do you print an array of elements in the same line in Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by comma use sep=”\n” or sep=”, ” respectively.

How do I print the full NumPy array without truncating?

In NumPy, it is possible to remove truncation and display results as it is. We use np. set_printoptions() function having attribute threshold=np. inf or threshold=sys.


1 Answers

In order to print a numpy.array into a single line, you can convert it to a list with its built-in function numpy.tolist()

Example:

import numpy as np

arr = np.array(((1, 2, 3), (4, 5, 6), (7, 8, 9)))

Simple print of array:

print(arr)
[[1, 2, 3]
 [4, 5, 6]
 [7, 8, 9]]

In comparison with numpy.tolist():

print(array.tolist())
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
like image 106
Christoph Engwer Avatar answered Sep 27 '22 20:09

Christoph Engwer