简体   繁体   中英

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

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

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

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM