Indexing with a list? Is it possible?

The way I am doing it now seems to be very clumsy. Is there a better way to index this array?

This is the code that works:

DEM = np.empty((number_of_DEM_files, DEMfile.shape[0], DEMfile.shape[1]), 'float')

for t in range(number_of_DEM_files):
      DEM[t] = np.load(DEM_filename_list[t])

      

I tried to do it with a list of concepts like this:

DEM = np.load([DEM_filename_list[t] for t in range(number_of_DEM_files)])

      

but I am getting syntax error. Is it possible? Is there even a reason for this or is it as slow as what I already have? Is there a better way?

EDIT:

DEM_filename_list looks like this:

DEM_filename_list = (D:/Documents/Data/grand_canyon_2015/03-11/dem1.npy,
                     D:/Documents/Data/grand_canyon_2015/03-11/dem2.npy,
                     D:/Documents/Data/grand_canyon_2015/03-11/dem3.npy,
                     etc)

      

The first line creates an empty 3d array. Ultimately I am trying to load and store the time series of the arrays in a single 3D array so that you can index it with DEM [t, I, J]

where t is time, i is the row number, j is the column number.

+3


source to share


3 answers


This is a test case that works great:

import numpy as np

a = np.array((1,2))
b = np.array((3,4))

with open('12', 'wb') as f:
    np.save(f,a)
with open('34', 'wb') as f:
    np.save(f,b)    

l = DEM_filename_list

DEM = [np.load(ll) for ll in l]

print DEM

      

Output:

[array([1, 2]), array([3, 4])]

      

Or your annotations are presented:

import numpy as np

DEM = [np.load(ll) for ll in DEM_filename_list]

print DEM

      



Output:

 DEM_files

      

UPDATED:

No need for the line:

DEM = np.empty((number_of_DEM_files))

      

+1


source


I'm not sure if number_of_DEM_files is directly related to DEM_filename_list , I assume it is one to one and DEM_filename_list is iterable (by name), in which case I would do something like this.

DEM = np.empty((number_of_DEM_files, DEMfile.shape[0], DEMfile.shape[1])

for i, t in enumerate(DEM_filename_list):
      DEM[i] = np.load(t)

      



or

DEM = [np.load(t) for t in DEM_filename_list]

      

+1


source


You can use the built-in function enumerate to get an enumeration object (index, value) and use the index in the resulting pair.

If performance is an issue, you can use the numpy: ndenumerate enumeration function .

-1


source







All Articles