'How to print numpy objects without line breaks

I am logging input arguments to a function using

logging.debug('Input to this function = %s',
              inspect.getargvalues(inspect.currentframe())[3])

But I do not want the line breaks inserted within numpy objects. numpy.set_printoptions(linewidth=np.nan) removes some, but line breaks are still inserted in 2D objects such as

array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ],
       [ 0.68041249,  0.20310698,  0.89486761,  0.97799646],
       [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])

I want it to be like this:

array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ], [ 0.68041249,  0.20310698,  0.89486761,  0.97799646], [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])

How can I do this? Thanks.



Solution 1:[1]

Given an array x, you can print it without line breaks with,

import numpy as np
x_str = np.array_repr(x).replace('\n', '')
print(x_str)

or alternatively using the function np.array2string instead of np.array_repr.

I'm not sure if there is an easy way to remove newlines from the string representation or numpy arrays. However, it is always possible to remove them after the conversion took place,

input_args = inspect.getargvalues(inspect.currentframe())[3]
logging.debug('Input to this function = %s', repr(input_args).replace('\n', ''))

Solution 2:[2]

import numpy as np
np.set_printoptions(threshold=np.inf)
np.set_printoptions(linewidth=np.inf)

# Testing:
big_arr = np.ones([30,70])
print(big_arr)

Solution 3:[3]

Simple solution

import numpy as np
value = np.array([[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 7, 8]])

value_str = str(value).replace('\n', '')  

print("prints: " + value_str)
# prints: [[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 7, 8]]

Solution 4:[4]

This solution also works:

myArray = np.array([[ 0.84148239,  0.71467895,  0.00946744,  0.3471317 ],
       [ 0.68041249,  0.20310698,  0.89486761,  0.97799646],
       [ 0.22328803,  0.32401271,  0.96479887,  0.43404245]])

print(np.array2string(myArray).replace('\n','').replace(' ',', '))

Output:

[[0.84148239, 0.71467895, 0.00946744, 0.3471317, ], [0.68041249, 0.20310698, 0.89486761, 0.97799646], [0.22328803, 0.32401271, 0.96479887, 0.43404245]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Osi
Solution 3 niek tuytel
Solution 4 Davi Areias