Vortex.ihrc.fiu.edu



Python Input and Output1. Numpy ‘save’ and ‘load’>>> import numpy as np>>> matrix=np.random.random((10,10,42))>>> nx,ny,nz=np.shape(matrix)>>> CXY=np.zeros([ny, nx])>>> for i in range(ny): for j in range(nx): CXY[i,j]=np.max(matrix[j,i,:])>>> np.save("maximums.npy", CXY)>>> np.save(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\maximums.npy", CXY)>>> CXY=np.load(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\maximums.npy")If you want to save multiple arrays in a file, then, you could do this,>>> x = np.arange(10)>>> y = np.sin(x)>>> np.save(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2',(x,y))>>> np.load(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.npy')array([[ 0. , 1. , 2. , 3. , 4. , 5. , 6. , 7. , 8. , 9. ], [ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 , -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849]])Note that the following codes do not work!>>> np.save(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy", x,y)>>> np.load(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy")array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> np.save(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy", y, x)>>> np.load(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy")array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 , -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])Also note that in this case, variables ‘x’ and ‘y’ have the same dimension. But what if variables have different dimension? For example, we want to save x and CXY in a file. Let’s try this,>>> np.save(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2',(x,CXY))Traceback (most recent call last): File "<pyshell#94>", line 1, in <module> np.save(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2',(x,CXY)) File "C:\Anaconda3\Lib\site-packages\numpy\lib\npyio.py", line 489, in save arr = np.asanyarray(arr) File "C:\Anaconda3\Lib\site-packages\numpy\core\numeric.py", line 533, in asanyarray return array(a, dtype, copy=False, order=order, subok=True)ValueError: could not broadcast input array from shape (10,10) into shape (10)So, if variables do not have the same dimension, then, we cannot use this method to write these variables into a file. 2. Numpy ‘savez’If you want to write multiple arrays to a file, then, you can use ‘savez’, which bundle serval arrays into a single in uncompressed .npz format. For example,>>> np.savez(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy", x,y)This also works,>>> np.savez(r'D:\Users\zhup\wrk\course\course10\python\output\test1.npy', x,y)But not,>>> np.savez(r'D:\Users\zhup\wrk\course\course10\python\output\test1.npy", x,y)>>> np.savez(r"D:\Users\zhup\wrk\course\course10\python\output\test1.npy', x,y)>>> npzfile=np.load(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy.npz")>>> npzfile.files['arr_0', 'arr_1']>>> npzfile['arr_0']array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> npzfile['arr_1']array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 , -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])>>> np.savez(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy", x=x,y=y)>>> npzfile=np.load(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy.npz")>>> npzfile.files['x', 'y']>>> npzfile['x']array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> npzfile['y']array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 , -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])>>> x1=npzfile['x']>>> y1=npzfile['y']>>> np.savez(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy",x,y,CXY)>>> npzfile=np.load(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy.npz")>>> npzfile.files['arr_1', 'arr_0', 'arr_2']>>> npzfile['arr_1']>>> npzfile['arr_0']>>> npzfile['arr_2']>>>np.savez(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy",x=x,y=y,CXY=CXY)>>> npzfile=np.load(r"D:\Users\zhup\wrk\course\course10\2017\Lect06\test1.npy.npz")>>> npzfile.files['y', 'x', 'CXY']>>> npzfile['x']>>> npzfile['y']>>> npzfile['CXY']3. Numpy ‘savetxt’ and loadtxtYou can also save data in txt format, for example, >>>np.savetxt(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt',CXY)>>> npzfile=np.loadtxt(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt')>>> npzfile.shape(10, 10)Similarly, you can save multiple arrays with the same dimension like this,>>> np.savetxt(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt',(x,y))>>> np.loadtxt(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt')array([[ 0. , 1. , 2. , 3. , 4. , 5. , 6. , 7. , 8. , 9. ], [ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 , -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849]])If you want to save multiple arrays with the different dimensions, you could append arrays one after another like this,>>> f=open(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt','wb')>>> np.savetxt(f,x)>>> np.savetxt(f,CXY)>>> np.savetxt(f,y)>>> f.close()Here, ‘wb’ means ‘open for writing in binary mode’. Although the three variables are written to the file one by one, we cannot use ‘loadtxt’ to read it since the dimensions are different.>>> np.loadtxt(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt')Traceback (most recent call last): File "<pyshell#167>", line 1, in <module> np.loadtxt(r'D:\Users\zhup\wrk\course\course10\python\output\test2.txt') File "C:\Anaconda3\Lib\site-packages\numpy\lib\npyio.py", line 927, in loadtxt % line_num)ValueError: Wrong number of columns at line 11Since ‘loadtxt’ only reads 1D array, we may solve this problem by reshaping CXY to 1D array,>>> f=open(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt','wb')>>> np.savetxt(f,x)>>> np.savetxt(f,CXY.reshape(100,1))>>> np.savetxt(f,y)>>> f.close()>>> comb_array=np.loadtxt(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt')4. Python write() and read()Numpy ‘save’, ‘savez’, ‘savetxt’, ‘load’, and ‘loadtxt’ are good for arrays with numbers. Sometimes, we can also use Python write() and read() to do output and input.open() functionSyntax: file_object=(file_name, access_mode), for example,>>> f=open('test2.txt','wb')>>> f=open(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt','wb')Examples:>>> f=open(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test3.txt','w')>>> f.write( "Python is a great language.\nYeah its great!!\n")45>>> f.write("Art: %5d, price per Unit: %8.2f" % (453, 59.058))36>>> f.close()>>> f=open(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test3.txt','r+')>>> f.read()'Python is a great language.\nYeah its great!!\nArt: 453, price per Unit: 59.06'>>> f.close()5. Output formatThe general syntax for a format placeholder is,%[width][.precision]typeFor example, >>> print("%6.2f"% (23.789)) 23.79>>> print("%6.2f"% (0.039)) 0.04>>> print("%6.2f"% (199.8))199.80>>> print("%6.2f"% (23)) 23.00>>> print("%6.2f"% (2324.17))2324.17ConversionMeaningdSigned integer decimal.iSigned integer decimal.oUnsigned octal.uUnsigned decimal.xUnsigned hexadecimal (lowercase).XUnsigned hexadecimal (uppercase).eFloating point exponential format (lowercase).EFloating point exponential format (uppercase).fFloating point decimal format.FFloating point decimal format.gSame as "e" if exponent is greater than -4 or less than precision, "f" otherwise.GSame as "E" if exponent is greater than -4 or less than precision, "F" otherwise.cSingle character (accepts integer or single character string).rString (converts any python object using repr()).sString (converts any python object using str()).%No argument is converted, results in a "%" character in the result.More examples,>>> print("%10.3e"% (356.08977)) 3.561e+02>>> print("%10.3E"% (356.08977)) 3.561E+02>>> print("%10.4e"% (356.08977))3.5609e+02>>> print("%14.8e"% (356.08977))3.56089770e+02>>> print("%d"% (356.08977))356>>> print("%3d"% (356.08977))356>>> print("%i"% (356.08977))356Go back to the previous example,>>> x = np.arange(10)>>> y = np.sin(x)>>> np.savetxt(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt',x,fmt='%2d')>>> np.savetxt(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt',x,fmt='%6.2f')>>> np.savetxt(r'D:\Users\zhup\wrk\course\course10\2017\Lect06\test2.txt',y,fmt='%6.2f')Now, let’s say we want save x and y in a file in the following format, 0. , 0.00 1. , 0.84 2. , 0.91 3. , 0.14 4. , -0.76 5. , -0.96 6. , -0.28 7. , 0.66 8. , 0.99 9. , 0.41>>> xarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> yarray([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 , -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])>>> x.reshape(10,1)array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]])>>> y.reshape(10,1)array([[ 0. ], [ 0.84147098], [ 0.90929743], [ 0.14112001], [-0.7568025 ], [-0.95892427], [-0.2794155 ], [ 0.6569866 ], [ 0.98935825], [ 0.41211849]])>>> z=np.concatenate((x,y))>>> zarray([ 0. , 1. , 2. , 3. , 4. , 5. , 6. , 7. , 8. , 9. , 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 , -0.95892427, -0.2794155 , 0.6569866 , 0.98935825, 0.41211849])>>> z=np.concatenate((x.reshape(10,1),y.reshape(10,1)),axis=0)>>> zarray([[ 0. ], [ 1. ], [ 2. ], [ 3. ], [ 4. ], [ 5. ], [ 6. ], [ 7. ], [ 8. ], [ 9. ], [ 0. ], [ 0.84147098], [ 0.90929743], [ 0.14112001], [-0.7568025 ], [-0.95892427], [-0.2794155 ], [ 0.6569866 ], [ 0.98935825], [ 0.41211849]])>>> z=np.concatenate((x.reshape(10,1),y.reshape(10,1)),axis=1)>>> zarray([[ 0. , 0. ], [ 1. , 0.84147098], [ 2. , 0.90929743], [ 3. , 0.14112001], [ 4. , -0.7568025 ], [ 5. , -0.95892427], [ 6. , -0.2794155 ], [ 7. , 0.6569866 ], [ 8. , 0.98935825], [ 9. , 0.41211849]])>>> np.savetxt(r'D:\Users\zhup\wrk\course\course10\python\output\test2.txt',z,fmt='%i %f')>>> np.loadtxt(r'D:\Users\zhup\wrk\course\course10\python\output\test2.txt')array([[ 0. , 0. ], [ 1. , 0.841471], [ 2. , 0.909297], [ 3. , 0.14112 ], [ 4. , -0.756802], [ 5. , -0.958924], [ 6. , -0.279415], [ 7. , 0.656987], [ 8. , 0.989358], [ 9. , 0.412118]])>>> np.savetxt(r'D:\Users\zhup\wrk\course\course10\python\output\test2.txt',z,fmt='%i %6.2f')>>> np.loadtxt(r'D:\Users\zhup\wrk\course\course10\python\output\test2.txt')array([[ 0. , 0. ], [ 1. , 0.84], [ 2. , 0.91], [ 3. , 0.14], [ 4. , -0.76], [ 5. , -0.96], [ 6. , -0.28], [ 7. , 0.66], [ 8. , 0.99], [ 9. , 0.41]])Or you can change data type>>> x1=x.astype(float)>>> x = np.arange(10,dtype=np.float)6. Load Matlab data>>>import scipy.io>>>matfile=scipy.io.loadmat(r'D:\Users\zhup\wrk\analysis\ab_model\data\nond_2d_MK97.mat')>>> matfile{'t': array([[ ….'e': array([[ ….. 'r': array([[…>>> t=matfile['t']>>> e=matfile['e']>>> r=matfile['r']7. Load Netcdf data>>> from scipy.io import netcdf>>>f=cdf_file(r'D:\Users\zhup\wrk\analysis\Edouard\data\radar_edouard_N43_1720.nc', 'r')>>> f.variables{'v': <scipy.cdf_variable object at 0x00000000055CA400>, 'lonc': <scipy.cdf_variable object at 0x00000000058D1FD0>, 'ws': <scipy.cdf_variable object at 0x00000000055CA550>, 'w': <scipy.cdf_variable object at 0x00000000055CA470>, 'lon': <scipy.cdf_variable object at 0x00000000058D4FD0>, 'lat': <scipy.cdf_variable object at 0x00000000058D4DA0>, 'latc': <scipy.cdf_variable object at 0x00000000058D4BE0>, 'dbz': <scipy.cdf_variable object at 0x00000000055CA4E0>, 'z': <scipy.cdf_variable object at 0x00000000055CA048>, 'u': <scipy.cdf_variable object at 0x00000000055CA4A8>}>>> dbz=f.variables['dbz']>>> dbz=np.array(list(dbz))>>> dbz.shape(99, 101, 37) ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download