Null numpy array to add to

I am writing a function selection code. Basically get the result of the featureelection function and combine it with a numpy dataset

data=np.zeros([1,4114]) # put feature length here for i in range(1,N): filename=splitpath+str(i)+'.tiff' feature=featureselection(filename) data=np.vstack((data, feature)) data=data[1:,:] # remove the first zeros row 

However, this is not a reliable implementation, since I need to know in advance the length of the element (4114).

Is there a null matrix array numpy like in the Python list we have []?

+4
source share
2 answers

Adding numpy to the array in a loop is inefficient; there may be situations where they cannot be avoided, but this does not seem to be one of them. If you know the size of the array you are going to end in, the best thing is to simply allocate the array, something like this:

 data = np.zeros([N, 4114]) for i in range(1, N): filename = splitpath+str(i)+'.tiff' feature = featureselection(filename) data[i] = feature 

Sometimes you donโ€™t know the size of the final array. There are several ways to deal with this case, but the simplest is probably to use a temporary list, for example:

 data = [] for i in range(1,N): filename = splitpath+str(i)+'.tiff' feature = featureselection(filename) data.append(feature) data = np.array(data) 

Just for completeness, you can also do data = np.zeros([0, 4114]) , but I would recommend against this and suggest one of the methods above.

+3
source

If you do not want to assume size before creating the first array, you can use lazy initialization.

 data = None for i in range(1,N): filename=splitpath+str(i)+'.tiff' feature=featureselection(filename) if data is None: data = np.zeros(( 0, feature.size )) data = np.vstack((data, feature)) if data is None: print 'no features' else: print data.shape 
+1
source

All Articles