Python shape函数获取数组大小

本文介绍了Python Numpy库中ndarray.shape属性的使用,该属性用于获取和改变数组的尺寸。通过shape,我们可以得知数组的维度信息。当shape中某个维度设为-1时,其大小将根据数组总元素数量和其他维度自动计算。文中提到一个未解的示例,期待读者解答。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

语句格式:

    ndarray.shape

返回值:

    数组维度的元组。

    数组的shape属性常用语获取一个数组的当前大小,与reshape函数相似,shape函数也可以更改数组大小,其中一个维度的大小可为-1,表明该处大小从数组的原size和剩余dimensions推算而来。

示例:

    最后一个示例没看懂,哪位高手能帮忙解答吗?

Numpy文档原文:

numpy.ndarray.shape

ndarray. shape

Tuple of array dimensions.

The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required.

See also

numpy.reshape
similar function
ndarray.reshape
similar method

Examples

>>> x = np.array([1, 2, 3, 4])
>>> x.shape
(4,)
>>> y = np.zeros((2, 3, 4))
>>> y.shape
(2, 3, 4)
>>> y.shape = (3, 8)
>>> y
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
>>> y.shape = (3, 6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: total size of new array must be unchanged
>>> np.zeros((4,2))[::2].shape = (-1,)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: incompatible shape for a non-contiguous array

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值