简体   繁体   中英

Writing an ASCII file from a 2D numpy array

I have a 2D numpy array. I want to make a ASCII file out of it. Here's the code I am using where a3 is the numpy array

f = open('ASCIIout.asc', 'w')
numpy.savetxt(ASCIIout, a3)
f.write("ncols " + str(ncols) + "\n")
f.write("nrows " + str(nrows) + "\n")
f.write("xllcorner " + str(xllcorner) + "\n")
f.write("yllcorner " + str(yllcorner) + "\n")
f.write("cellsize " + str(cellsize) + "\n")
f.write("NODATA_value " + str(noDATA) + "\n")
f.close()

Now I open it with append option and write the 2D array values:

f_handle = open(ASCIIout, 'a')
numpy.savetxt(f_handle, MyArray, fmt="%.3f")
f_handle.close()

However, I have a couple problems. First, the fmt really does not work I get values like this:

9.999000000000000000e+03 

If I JUST use the code below line of code, I get -9999.000 1.345 , but then, I haven't attached ncols, nrows, etc to the ASCII file.

numpy.savetxt(f_handle, MyArray, fmt="%.3f")

My data range from 0 to 6. What I really want to get is:

-9999 1.345 -9999 3.21 0.13 -9999

where I do NOT get decimals after -9999 and I do get decimals after real data such as 1.345 I made the ASCII file in R, I am wondering there should be a easy way to do it in Python. Thanks for your help in advance.

If your intention is to have the "stop value" -9999 appear without the decimal point, you can let savetxt() save all the values with the "%.3f" format, and replace the one result you don't want with the one you want:

from StringIO import StringIO
import numpy as np
f = StringIO()
x = np.array(( -9999, 1.345, -9999, 3.21, 0.13, -9999), dtype=float)
np.savetxt(f, x, fmt='%.3f')
f.seek(0)
fs = f.read().replace('-9999.000', '-9999', -1)
f.close()
f = open('ASCIIout.asc', 'w')
f.write("ncols " + str(ncols) + "\n")
f.write("nrows " + str(nrows) + "\n")
f.write("xllcorner " + str(xllcorner) + "\n")
f.write("yllcorner " + str(yllcorner) + "\n")
f.write("cellsize " + str(cellsize) + "\n")
f.write("NODATA_value " + str(noDATA) + "\n")
f.write(fs)
f.close()

If you want all the integer values represented without decimals, .replace('.000', '', -1) would accomplish that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM