Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array is printed into file with unwanted wrapping

Tags:

python

numpy

I have a number of lengthy vectors like below:

a = np.array([ 57.78307975,  80.69239616,  80.9268784,   62.03157284,  61.57220483,  67.99433377,  68.18790282])

When I print it into file with:

outfile.write(str(a))
# or
outfile.write(np.array_str(a))

It automatically wraps the middle of a line up and it makes the vector occupy two lines:

[ 57.78307975  80.69239616  80.9268784   62.03157284  61.57220483
  67.99433377  68.18790282]

The wrapped line has a width of 66. I'm not sure whether this value is related with a width of terminal screen.

I just want to see a vector be printed in a single line. How can I make it?

like image 473
Jeon Avatar asked Apr 04 '14 13:04

Jeon


People also ask

How do I stop NumPy from printing in scientific notation?

Approach: Import numpy library and create numpy array. Pass the supress value as True to the set_printoptions() method. Print the Array, The entire array will be displayed without scientific notation.

How do you deal with a large NumPy array?

Sometimes, we need to deal with NumPy arrays that are too big to fit in the system memory. A common solution is to use memory mapping and implement out-of-core computations. The array is stored in a file on the hard drive, and we create a memory-mapped object to this file that can be used as a regular NumPy array.


1 Answers

This is because the default print option "linewidth" is 75:

>>> np.get_printoptions()['linewidth']
75

To disable wrapping you can set the linewidth to infinite with np.set_printoptions:

>>> str(a)
'[57.78307975 80.69239616 80.9268784  62.03157284 61.57220483 67.99433377\n 68.18790282]'
>>> np.set_printoptions(linewidth=np.inf)
>>> str(a)
'[57.78307975 80.69239616 80.9268784  62.03157284 61.57220483 67.99433377 68.18790282]'

For a once-off override, without needing to alter the global options:

>>> np.array2string(a, max_line_width=np.inf)
'[57.78307975 80.69239616 80.9268784  62.03157284 61.57220483 67.99433377 68.18790282]'
like image 79
wim Avatar answered Oct 18 '22 20:10

wim