如何解决Numpy:二维数组矩阵的大小?
我下面的 2 个语句在内部机制上有何不同,而它们却给出相同的输出?
x = np.array([[**1,2,3,6,7,8**],[**4,5,8,9,5**]])
np.size(x)
x.size
两个都是正确的输出,因为数组的大小是 12。
解决方法
在这种情况下,未指定轴 sp 时,内部 np.size(x)
调用 x.size
,结果相同。
if axis is None:
try:
return a.size
except AttributeError:
return asarray(a).size
但是,如果您指定 axis
,则结果会有所不同。
>>> a=np.arange(16).reshape(4,4)
>>> a.shape
(4,4)
>>> np.size(a,axis=1)
4
>>> a.size
16
,
np.size
接受参数轴; x.size
总是返回元素的总数:
def size(a,axis=None):
"""
Return the number of elements along a given axis.
Parameters
----------
a : array_like
Input data.
axis : int,optional
Axis along which the elements are counted. By default,give
the total number of elements.
Returns
-------
element_count : int
Number of elements along the specified axis.
See Also
--------
shape : dimensions of array
ndarray.shape : dimensions of array
ndarray.size : number of elements in array
Examples
--------
>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
"""
if axis is None:
try:
return a.size
except AttributeError:
return asarray(a).size
else:
try:
return a.shape[axis]
except AttributeError:
return asarray(a).shape[axis]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。