简体   繁体   English

numpy,如何在二维数组中找到总行数,在一维数组中找到总列数

[英]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]] [[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来做到这一点:

#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. Numpy的函数通常采用axis参数,就2D数组而言, axis=0将跨列应用函数,而axis=1将跨行应用此函数。

>>> 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. 因此,如果你有n维数组,你可以找到所有维度,但你只需要随后附加[0]

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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