np.reshape 中的 -1 参数

本文详细解析了Numpy中reshape函数的使用方法,尤其对于-1参数的解释,帮助理解如何改变数组形状,同时保持元素数量不变。通过实例展示了如何指定未知维度,由Numpy自动计算。

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

根据Numpy文档(https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy-reshape)的解释:
newshape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

   大意是说,数组新的 shape 属性应该要与原来的配套,如果等于 -1 的话,那么Numpy会根据剩下的维度计算出数组的另外一个 newshape 属性值。

举几个例子或许就清楚了,有一个数组 z 如下:

  而 z.reshape(-1, 1) 是说,我们不知道新z的行数是多少,但是想让z变成只有一列,行数不知的新数组,通过z.reshape(-1,1),Numpy 自动计算出有 16 行,新的数组 shape 属性为 (16, 1),与原来的 (4, 4) 配套。

z.reshape(-1, 2),行数未知,列数等于 2,reshape 后的 shape 等于 (8, 2)

同理,只给定行数,列数未知,也可以设置 newshape 等于 -1,Numpy 也可以自动计算出新数组的列数。

作者:李彬
链接:https://www.zhihu.com/question/52684594/answer/157491724
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值