0

I am new to using NumPy and trying to work with arrays, tried building a 1D,2D and now a 3D array. But I wasn't sure why ndim thinks that this is a 2D array even though it has 3 rows

In [26]: c= array ([[1,1,1,1],[2,2,2,2],[3,3,3,3]])

In [27]: c
Out[27]: 
array([[1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3]])

In [28]: c.ndim
Out[28]: 2

This one shows up as a 3D array. How does the grouping work in a 3D array?

In [30]: d= array([[[1], [2]], [[3], [4]]])

In [31]: d
Out[31]: 
array([[[1],
        [2]],

       [[3],
        [4]]])

In [32]: d.ndim
Out[32]: 3
2
  • 1
    3 rows doesn't mean 3 dimensions. Commented Jan 27, 2014 at 2:32
  • Then what does dimension mean for an array? Commented Jan 27, 2014 at 2:35

4 Answers 4

3

Look at the nested list you're passing to the array constructor. What kind of expression would you use to retrieve an element?

A[i][j]    # This?
A[i][j][k] # Or this?

If it's the first option, you have a 2D array. If it's the second option, you have a 3D array. The number of indexes you need is the dimension of the array. It has nothing to do with how many rows or columns are in it.

Sign up to request clarification or add additional context in comments.

Comments

0

The dimensions depend on the number of groupings, not the number of rows. The first example is an array of arrays, so it's 2D. The second is an array of arrays of arrays (with 1 number in them) so it's 3D.

Comments

0

Dimensions are different than items. In your situation, you can check if you have a 2d array by asking for the length,

len(c)

would give you 3, since you have 3 elements at the top index c. If you want to check how many elements are in each of those top three, you would do

len(c[0])
len(c[1])
len(c[2])

which would all give you 3. Then you can do c[0][0]. However, if you try to do

len(c[0][0][0])

you will get an error since the index c[0][0][0] is not a list or array, so it can not be indexed.

Your second example of a 3 dimensions can be indexed d[0][0][0] since

(*FIRST*[*SECOND*[*THIRD*[1],[2]],[[3],[4]]])

where FIRST is d, second is d[0], and third is d[0][0]

Comments

0

You're not talking about dimension. I think you're looking for shape:

In [8]: c.shape
Out[8]: (3, 4)

Which gives you rows and columns.

In [9]: c.ndim
Out[9]: 2

Gives number of dimensions you can index/subscript by. If you have a small raster of pixels as 2D, 3D would be a volume of voxels.

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.