Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

python - Very Basic Numpy array dimension visualization

I'm a beginner to numpy with no experience in matrices. I understand basic 1d and 2d arrays but I'm having trouble visualizing a 3d numpy array like the one below. How do the following python lists form a 3d array with height, length and width? Which are the rows and columns?

b = np.array([[[1, 2, 3],[4, 5, 6]],
          [[7, 8, 9],[10, 11, 12]]])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The anatomy of an ndarray in NumPy looks like this red cube below: (source: Physics Dept, Cornell Uni)

anatomy of nd array


Once you leave the 2D space and enter 3D or higher dimensional spaces, the concept of rows and columns doesn't make much sense anymore. But still you can intuitively understand 3D arrays. For instance, considering your example:

In [41]: b
Out[41]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])

In [42]: b.shape
Out[42]: (2, 2, 3)

Here the shape of b is (2, 2, 3). You can think about it like, we've two (2x3) matrices stacked to form a 3D array. To access the first matrix you index into the array b like b[0] and to access the second matrix, you index into the array b like b[1].

# gives you the 2D array (i.e. matrix) at position `0`
In [43]: b[0]
Out[43]: 
array([[1, 2, 3],
       [4, 5, 6]])


# gives you the 2D array (i.e. matrix) at position 1
In [44]: b[1]
Out[44]: 
array([[ 7,  8,  9],
       [10, 11, 12]])

However, if you enter 4D space or higher, it will be very hard to make any sense out of the arrays itself since we humans have hard time visualizing 4D and more dimensions. So, one would rather just consider the ndarray.shape attribute and work with it.


More information about how we build higher dimensional arrays using (nested) lists:

For 1D arrays, the array constructor needs a sequence (tuple, list, etc) but conventionally list is used.

In [51]: oneD = np.array([1, 2, 3,])    
In [52]: oneD.shape
Out[52]: (3,)

For 2D arrays, it's list of lists but can also be tuple of lists or tuple of tuples etc:

In [53]: twoD = np.array([[1, 2, 3], [4, 5, 6]])
In [54]: twoD.shape
Out[54]: (2, 3)

For 3D arrays, it's list of lists of lists:

In [55]: threeD = np.array([[[1, 2, 3], [2, 3, 4]], [[5, 6, 7], [6, 7, 8]]])

In [56]: threeD.shape
Out[56]: (2, 2, 3)

P.S. Internally, the ndarray is stored in a memory block as shown in the below picture. (source: Enthought)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...