Write NumPy array contents to a file in Python

坚强是说给别人听的谎言 提交于 2021-01-13 09:39:25

问题


I have a NumPy array that I'm trying to write to a file

outfile.write(str(myarray))

But, I get something that looks like this:

[    4.275000000e01   2.345000000e01  3.2135000000e-02    ]

My requirements are:

  1. To write the data within the array (and not the array braces [])
  2. To write the data with a certain number of trailing decimal places (say 6)

Normally, #2 would not be that hard, but I'm not sure how to handle it in conjunction with #1.

I also want to write the array on one line as a row. like this:

4.27500000  2.34500000  0.03213500000

回答1:


savetxt does the equivalent of:

In [631]: x=np.array([4.275000000e01,   2.345000000e01,  3.2135000000e-02])

In [632]: '%10.6f %10.6f %10.6f'%tuple(x)
Out[632]: ' 42.750000  23.450000   0.032135'

In [642]: outfile.write((' '.join(['%10.6f ']*x.size)+'\n\n') % tuple(x))
42.750000   23.450000    0.032135

It turns your one-dimensional array into a tuple and passes it off to the format statement, with a format specification for each item in the array.




回答2:


Try this:

>>> a = np.array([[1,2,3],[1,2,3],[1,2,3]])
>>> a
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])
>>> b = a.flatten()
>>> b
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
>>> >>> np.savetxt("array.txt",b,delimiter=' ',newline=' ')

Edited to write on a single line




回答3:


If by writing to a file you mean text file, then use numpy.savetxt:

import numpy as np
my_array = np.random.rand(10,4)
np.savetxt('my_filenmame', my_array, fmt='%4.6f', delimiter=' ')

would write my_array to my_filename with up to six decimal digits leaving a white space in between them.

After the OP's edit: if you want to write the whole array to one line, make sure your array has only one row:

np.savetxt('my_filenmame', my_array.reshape(1,rows*cols), fmt='%4.6f', delimiter=' ')

where in this case rows=10 and cols=4. Or use ravel or flatten (see also Harpal's answer, although that does not answer the decimal precision issue)

np.savetxt('my_filenmame', my_array.ravel(), fmt='%4.6f', delimiter=' ', newline=' ')


来源:https://stackoverflow.com/questions/32082961/write-numpy-array-contents-to-a-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!