2

I would like to save an array with shape (5,2), the array named sorted_cube_station_list.

In the print it looks ok, but when I save it with numpy.tofile and later read it with numpy.fromfile it becames a 1d array

Can you help me with that? import numpy as num

nx=5
ny=5
nz=5
stations=['L001','L002','L003','L004','L005']

for x in range(nx):
    for y in range (ny):
         for z in range (nz):
             cube_station_list = []
             i=-1
             for sta in stations:
                 i=i+1
                 cube=[int(i), num.random.randint(2500, size=1)[0]]
                 cube_station_list.append(cube)
             cub_station_list_arr=num.asarray(cube_station_list)
             sorted_cube_station_list_arr=cub_station_list_arr[cub_station_list_arr[:, 1].argsort()]
             print x,y,z, sorted_cube_station_list_arr
             num.ndarray.tofile(sorted_cube_station_list_arr,str(x)+'_'+str(y)+'_'+str(z)
4
  • 1
    Any reason not to use np.save() ? Commented Sep 24, 2015 at 15:05
  • 1
    Also, your indentation (8 spaces) makes your code difficult to read, could you use 4 only ? Commented Sep 24, 2015 at 15:09
  • numpy.ndarray' object has no attribute 'write' that's why I didn't used it @M.Massias Commented Sep 24, 2015 at 15:11
  • 3
    Off topic, but you can replace the nested for loops with for x,y,z in np.ndindex((nx,ny,nz)): Commented Sep 24, 2015 at 15:13

1 Answer 1

6

I suggest you use np.save

a = np.ones(16).reshape([8, 2])
np.save("fileName.npy", a)

See the docs: first parameter must not be the variable you want to save, but the path to the file where you want to save it. Hence the error you got when using np.save(yourArray)

You can load the saved array using np.load(pathToArray)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.