44

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

2
  • 3
    What do you mean by "total rows"? Number of rows? Sum along the rows? Sum along the columns? Commented Sep 8, 2013 at 21:57
  • 1
    my bad for the ambiguity - its total rows and columns I wanted - which was answered previously below, thanks everyone for your generosities - great community!
    – Ahdee
    Commented Sep 9, 2013 at 2:55

5 Answers 5

60

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
1
  • 5
    Apparently this method fails to get shape for vectors
    – JenilDave
    Commented Sep 12, 2020 at 7:11
11
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]
9

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]
2
>>> 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.

1
  • HI Ophion, not exactly what I was looking for but helpful nonetheless, thanks!
    – Ahdee
    Commented Sep 8, 2013 at 23:14
2
>>> 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.