I want to create a multidimensional array with a predefined size. In C I would do the following:
int multi_array[5][6][7];
How do I create such thing in Python?
import numpy as np
a = np.ndarray((5,6,7), dtype=int)
note: This array will contain whatever junk happened to be in the unallocated memory at the time of creation. You may prefer to use this form if you are going to populate it with data later, for efficiency. Otherwise you might prefer to use np.zeros instead.
ndarray docs state: "Arrays should be constructed using array, zeros or empty" -- you're not really supposed to call the ndarray constructor except when inheriting from it, and advising new users to do so is a bad idea.np.empty and I can't see any obvious disadvantages..ndarray constructor is reserved for advanced use, not Numpy noobs. I'm not sure what extra control you need; I've got by with Numpy for several years without ever calling the constructor. np.empty takes shape, dtype and order. I must admit I never use buffers except at the Cython level using PyArray_SimpleNewFromData.keep in mind that numpy is a non-standard extension although you can find it on most systems nowadays. If you need to do this in pure python, you may try something like:
multi_array = []
for i in xrange(5):
list2 = []
for j in xrange(6):
list3 = []
for k in xrange(7):
list3.append(0)
list2.append(list3)
multi_array.append(list2)
of course a better approach is doing this on the fly (when loading the data or so) as python variables are not intended to be declared first as in C.