本文介绍了numpy.shape给出不一致的响应-为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么要程序
import numpy as np
c = np.array([1,2])
print(c.shape)
d = np.array([[1],[2]]).transpose()
print(d.shape)
给予
(2,)
(1,2)
作为其输出?不应该吧
(1,2)
(1,2)
而不是?我在python 2.7.3和python 3.2.3中都得到了这个
instead? I got this in both python 2.7.3 and python 3.2.3
推荐答案
当调用ndarray
的.shape
属性时,您将获得一个元组,其中的元素与数组的维数一样多.长度(即行数)是第一个维度(shape[0]
)
When you invoke the .shape
attribute of a ndarray
, you get a tuple with as many elements as dimensions of your array. The length, ie, the number of rows, is the first dimension (shape[0]
)
- 您从一个数组开始:
c=np.array([1,2])
.那是一个普通的一维数组,所以它的形状将是一个1元素的元组,而shape[0]
是元素的数量,所以c.shape = (2,)
- 考虑
c=np.array([[1,2]])
.那是一个2D数组,只有1行.第一行也是唯一的行是[1,2]
,这给了我们两列.因此,c.shape=(1,2)
和len(c)=1
- 考虑
c=np.array([[1,],[2,]])
.另一个2行2列1列的2D数组:c.shape=(2,1)
和len(c)=2
. - 考虑
d=np.array([[1,],[2,]]).transpose()
:此数组与np.array([[1,2]])
相同,因此其形状为(1,2)
.
- You start with an array :
c=np.array([1,2])
. That's a plain 1D array, so its shape will be a 1-element tuple, andshape[0]
is the number of elements, soc.shape = (2,)
- Consider
c=np.array([[1,2]])
. That's a 2D array, with 1 row. The first and only row is[1,2]
, that gives us two columns. Therefore,c.shape=(1,2)
andlen(c)=1
- Consider
c=np.array([[1,],[2,]])
. Another 2D array, with 2 rows, 1 column:c.shape=(2,1)
andlen(c)=2
. - Consider
d=np.array([[1,],[2,]]).transpose()
: this array is the same asnp.array([[1,2]])
, therefore its shape is(1,2)
.
另一个有用的属性是.size
:这是所有维度上的元素数,您需要数组c
c.size = np.product(c.shape)
.
Another useful attribute is .size
: that's the number of elements across all dimensions, and you have for an array c
c.size = np.product(c.shape)
.
文档中有关形状的详细信息.
More information on the shape in the documentation.
这篇关于numpy.shape给出不一致的响应-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!