user974666
user974666

Reputation: 379

python/numpy: how to get 2D array column length?

How do i get the length of the column in a nD array?

example, i have a nD array called a. when i print a.shape, it returns (1,21). I want to do a for loop, in the range of the column size of the array a. How do i get the value of

Upvotes: 33

Views: 99759

Answers (4)

PyMatFlow
PyMatFlow

Reputation: 478

Using the shape and size works well when you define a two dimension array, but when you define a simple array, these methods do not work For example :

K = np.array([0,2,0])

K.shape[1] and numpy.size(K,1)

produce an error in python :

Traceback (most recent call last):
  File "<ipython-input-46-e09d33390b10>", line 1, in <module>
    K.shape[1]
IndexError: tuple index out of range

Solution :

It solved by adding a simple option to array,

K = np.array([0,2,0],ndmin = 2)


K.shape[0]
Out[56]: 1

K.shape[1]
Out[57]: 3

np.size(K,0)
Out[58]: 1

np.size(K,1)
Out[59]: 3

More information :

https://codewithkazem.com/array-shape1-indexerror-tuple-index-out-of-range/

Upvotes: 3

Camilo
Camilo

Reputation: 41

You could use np.size(element,dimension).

In your case:

a.shape
>> (1, 21)


np.size(a,0)
>> 1

np.size(a,1)
>> 21

Upvotes: 4

icebelle
icebelle

Reputation: 15

enter image description here

this is a simple example, and you can follow it.By the way,the last statement should be corrected as "print b.shape[0]"

Upvotes: -2

DaveP
DaveP

Reputation: 7102

You can get the second dimension of the array as:

a.shape[1]

Upvotes: 60

Related Questions