问题描述
Python numpy数组'size'令我非常困惑
Python numpy array 'size' confuses me a lot
a = np.array([1,2,3])
a.size = (3, )
------------------------
b = np.array([[2,1,3,5],
[2,2,5,1],
[3,6,99,5]])
b.size = (3,4)
'b'很有意义,因为每个都有3行和4列但是'a'的大小如何=(3,)?因为它的1行3列,它应该不是(1,3)吗?
'b' makes sense since it has 3 rows and 4 columns in eachBut how is 'a' size = (3, ) ? Shouldn't it be (1,3) since its 1 row and 3 columns?
推荐答案
您应该抵制将numpy
数组视为具有行和列的冲动,但是而是认为它们具有尺寸和形状.这是区分np.array
和np.matrix
的重要点:
You should resist the urge to think of numpy
arrays as having rows and columns, but instead consider them as having dimensions and shape. This is an important point which differentiates np.array
and np.matrix
:
x = np.array([1, 2, 3])
print(x.ndim, x.shape) # 1 (3,)
y = np.matrix([1, 2, 3])
print(y.ndim, y.shape) # 2 (1, 3)
一个 n -D数组只能使用 n 整数表示其形状.因此,一维数组仅使用1个整数来指定其形状.
An n-D array can only use n integer(s) to represent its shape. Therefore, a 1-D array only uses 1 integer to specify its shape.
在实践中,对于numpy
来说,将一维和二维数组之间的计算组合起来并不是问题,并且从语法上讲,由于Python 3.5中引入了@
矩阵运算,因此在语法上是干净的.因此,很少有必要使用np.matrix
来满足查看预期的行数和列数的冲动.
In practice, combining calculations between 1-D and 2-D arrays is not a problem for numpy
, and syntactically clean since @
matrix operation was introduced in Python 3.5. Therefore, there is rarely a need to resort to np.matrix
in order to satisfy the urge to see expected row and column counts.
在极少需要2维的情况下,您仍然可以通过一些操作使用numpy.array
:
In the rare instances where 2 dimensions are required, you can still use numpy.array
with some manipulation:
a = np.array([1, 2, 3])[:, None] # equivalent to np.array([[1], [2], [3]])
print(a.ndim, a.shape) # 2 (3, 1)
b = np.array([[1, 2, 3]]) # equivalent to np.array([1, 2, 3])[:, None].T
print(b.ndim, b.shape) # 2 (1, 3)
这篇关于numpy数组大小混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!