Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print numpy objects without line breaks

Tags:

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.

like image 663
spark Avatar asked Mar 17 '15 15:03

spark


People also ask

How do you print an array on a single line in Python?

When you wish to print the list elements in a single line with the spaces in between, you can make use of the "*" operator for the same. Using this operator, you can print all the elements of the list in a new separate line with spaces in between every element using sep attribute such as sep=”/n” or sep=”,”.

How do you limit the number of items printed in output of a NumPy array?

To limit the values of the NumPy array ndarray to given range, use np. clip() or clip() method of ndarray . By specifying the minimum and maximum values in the argument, the out-of-range values are replaced with those values. This is useful when you want to limit the values to a range such as 0.0 ~ 1.0 or 0 ~ 255 .


3 Answers

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', ''))
like image 159
rth Avatar answered Oct 22 '22 20:10

rth


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]]
like image 20
niek tuytel Avatar answered Oct 22 '22 20:10

niek tuytel


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)
like image 25
Osi Avatar answered Oct 22 '22 19:10

Osi