2

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?

3 Answers 3

5
np.empty((5, 6, 7), dtype=int)

or, if you want it zero-filled,

np.zeros((5, 6, 7), dtype=int)
Sign up to request clarification or add additional context in comments.

Comments

3
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.

4 Comments

-1 (sorry); the 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.
Thanks, I wasn't aware of this. I have used this form of constructor in a lot of my old code, is there any danger? It has advantage of more control than np.empty and I can't see any obvious disadvantages..
I don't think there's much danger, it's just that the 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.
I think I needed strides once for some reason to do with boost::python and wrapping some performance critical C++ code, but it was years ago and I can't remember the details now
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.