Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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

like image 575
user974666 Avatar asked Oct 06 '11 04:10

user974666


People also ask

How do you count the number of columns in a 2D NumPy array?

In the NumPy with the help of shape() function, we can find the number of rows and columns. In this function, we pass a matrix and it will return row and column number of the matrix. Return: The number of rows and columns.

How do you determine the size of a 2D array?

We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.

How do I find the size of an array in NumPy?

Use ndim attribute available with numpy array as numpy_array_name. ndim to get the number of dimensions. Alternatively, we can use shape attribute to get the size of each dimension and then use len() function for the number of dimensions.


3 Answers

You can get the second dimension of the array as:

a.shape[1] 
like image 82
DaveP Avatar answered Sep 23 '22 12:09

DaveP


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

In your case:

a.shape >> (1, 21)   np.size(a,0) >> 1  np.size(a,1) >> 21 
like image 41
Camilo Avatar answered Sep 24 '22 12:09

Camilo


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/

like image 45
PyMatFlow Avatar answered Sep 25 '22 12:09

PyMatFlow