numpy, how do I find total rows in a 2D array and total column in a 1D array

Question:

Hi apologies for the newbie question, but I’m wondering if someone can help me with two questions.
Example say I have this,

[[1,2,3],[10,2,2]]

I have two questions.

  • How do I find total columns:
  • How do I find total rows:

thank you very much.
A

Asked By: Ahdee

||

Answers:

>>> import numpy as np
>>> a=np.array([[1,2,3],[10,2,2]])
>>> a
array([[ 1,  2,  3],
       [10,  2,  2]])

#Mean of rows.
>>> np.mean(a,axis=1)
array([ 2.        ,  4.66666667])

#Mean of columns.
>>> np.mean(a,axis=0)
array([ 5.5,  2. ,  2.5])

You can also do this with sum:

#Sum of rows.
>>> np.sum(a,axis=1)
array([ 6, 14])

#Sum of columns
>>> np.sum(a,axis=0)
array([11,  4,  5])

Numpy’s function will usually take an axis argument, in terms of a 2D array axis=0 will apply the function across columns while axis=1 will apply this across rows.

Answered By: Daniel

Getting number of rows and columns is as simple as:

>>> import numpy as np
>>> a=np.array([[1,2,3],[10,2,2]])
>>> num_rows, num_cols = a.shape
>>> print num_rows, num_cols
2 3
Answered By: jabaldonedo
import numpy as np
a = np.array([[1,2,3],[10,2,2]])
num_rows = np.shape(a)[0]
num_columns = np.shape(a)[1]
Answered By: Mohit Rai
>>> import numpy as np
>>> a=np.array([[1,2,3],[10,2,2]])
>>> row_count = len(a[:])
>>> col_count = len(a[:][0])
>>> print ("Row_Count:%d   Col_Count:%d " %(row_count,col_count))
Row_Count:2   Col_Count:3

So, if you have n-dimension array you can find all dimensions , but you just need to append [0] subsequently.

Answered By: Pratik Patel

There are multiple ways of doing this, one of them is as below:

import numpy as np
a = np.array([[1,2],[10,20],[30,20]])

# Total Rows: 
np.shape(a)[0]

#Total Columns: 
np.shape(a)[1]
Answered By: s_mj
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.