python:shape和reshape函数基本讲解

博客介绍了Python中shape和reshape函数。shape函数可了解数组结构,reshape函数能改变数组结构。还给出了两个函数的举例,同时提到运行代码会涉及tuple概念,使用reshape设定维度乘积要等于数组总量。

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

shape函数用来了解数组的结构;

reshape()函数用来对数组的结构进行改变

Shape举例

import numpy as np

#对于一维的数据
data = np.array([1,2,3,4,5,6,7,8])
print(data.shape)
print(type(data.shape))
print(data.shape[0])

#对于二维的数据
data = np.array([[1,2,3,4],[5,6,7,8]])
print(data.shape)
print(type(data.shape))
print(data.shape[0])

#对于三维的数据
data = np.array([[[1,2], [3, 4]],[[5,6],[7,8]]])
print(data.shape)
print(type(data.shape))
print(data.shape[0])

注:运行上面代码,会引入python中的tuple的概念

Reshape举例


#一维数据初始化
data = np.array([1,2,3,4,5,6,7,8])
print(data)
print(data.reshape(2,4)) #将数据变为2×4数组
print(data.reshape(2,2,2)) #将数据变为2×2*2数组
print(data.reshape(-1,2)) #有的时候我们只想规定列的维度,不确定行的维度,可以使用使用-1,根据数据大小来分配行的维度
print(data.reshape(-1,2,2)) #上述方法可以扩展到多维上

注:reshape设定维度的乘积,应该等于数组中的总量

了解更多关于《计算机视觉与图形学》相关知识,请关注公众号:

在这里插入图片描述
下载我们视频中代码和相关讲义,请在公众号回复:计算机视觉课程资料

### Python NumPy 库中的 `reshape` 函数 #### 语法 `numpy.reshape(a, newshape, order='C')` - **a**: 要被重塑的数组。 - **newshape**: 整数或整数元组,表示新形状。如果提供了一个整数值,则返回一维数组;可以使用 `-1` 来自动推断维度大小。 - **order**: {'C', 'F', 'A'},可选,默认为 `'C'`。指定读取/写入元素的方式。 #### 使用示例 创建一个简单的二维数组并展示其原始形态: ```python import numpy as np # 创建初始矩阵 matrix = np.array([[1, 2, 3], [4, 5, 6]]) print(f"Original matrix:\n{matrix}") ``` 将上述二维数组转换成不同的一维或多维形式: ```python # 将二维数组展平为一维数组 flattened_array = np.reshape(matrix, -1) print(f"\nFlattened array using (-1):\n{flattened_array}") # 改变形状至特定尺寸(例如:3x2) reshaped_3_by_2 = np.reshape(matrix, (3, 2)) print(f"\nReshaped to shape (3, 2):\n{reshaped_3_by_2}") # 自动推算其中一个维度大小 auto_inferred_shape = np.reshape(matrix, (2, -1)) print(f"\nAuto inferred one dimension size with (2, -1):\n{auto_inferred_shape}") ``` 以上代码片段展示了如何利用 `np.reshape()` 方法来改变给定数组的形式而不影响原数据的内容[^1]。 当设置参数 `order` 不同时,会影响元素排列顺序。对于大多数情况,默认值 `"C"` 已经足够满足需求,它按照 C 风格连续存储模式操作数据。而选择 `"F"` 则遵循 Fortran 方式的列优先级访问模式[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值