python中numpy的reshape方法

numpy的reshape()方法用于将数据从新组织,由于保存记录方便查看

    import numpy as np

    a=np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
    a
    #运行结果
    array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])

    a.reshape(2,6)
    #运行结果
    >>>array([[ 1,  2,  3,  4,  5,  6],
              [ 7,  8,  9, 10, 11, 12]])


    a.reshape(-1,1)
    #运行结果,-1代表未指定行数
    >>>array([[ 1],
               [ 2],
               [ 3],
               [ 4],
               [ 5],
               [ 6],
               [ 7],
               [ 8],
               [ 9],
               [10],
               [11],
               [12]])

    a.reshape(1,-1)
    #运行结果,-1代表未指定列数
    array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]])    

 

### 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、付费专栏及课程。

余额充值