关于Python的Numpy库reshape()函数的用法

1.介绍

更改数组的形状,不改变原数组

2.语法

a = np.reshape(mat, newshape, order = ‘C’)
a : newshape形状的新数组
mat : 原数组
newshape:(1, 2)/ 1, 2 都可以改为1行2列的数组
order:读取原数组的规则,默认为C(C行优先,F按某种方式,但不是列优先!)
order暂时按这么理解。

3.使用

  1. b = np.reshape(a, newshape)
  2. b = a.reshape(newshape)

key:其中newshape中可以有参数-1,意义为模糊推测,如(-1, 2)我不管你有行,修改为2列的二维数组即可;如(3,-1)我不管你有几列,修改为3行的二维数组即可

3.1 order的引用示例

行优先:

import numpy as np

a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 修改为1,行12列数组,顺序读取
b = a.reshape(1, 12, order='C')
print("修改后:")
print(b)

在这里插入图片描述
F方式读取

import numpy as np

a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 修改为1行12列,按列优先读取
b = a.reshape(1, 12, order='F')
print("修改后:")
print(b)

在这里插入图片描述
非列优先

3.2 实际用法(一般order为默认值)

给定形状

import numpy as np

# 3行4列的二维数组
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 此时中间只剩newshape,2行6列
b = a.reshape(2,6)
print("修改后:")
print(b)

在这里插入图片描述

模糊推测,推测列

import numpy as np

# 3行4列的二维数组
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 此时中间只剩newshape,修改为6行的数组就行,多少列我不知道
b = a.reshape(6, -1)
print("修改后:")
print(b)

模糊推测,推测行

import numpy as np

# 3行4列的二维数组
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 此时中间只剩newshape,修改为3列的数组就行,多少行我不知道
b = a.reshape(-1, 3)
print("修改后:")
print(b)

在这里插入图片描述
模糊推测升维

import numpy as np

# 3行4列的二维数组
a = np.array([[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]])
print("原数组:")
print(a)
# 此时中间只剩newshape,修改为3行2列的子数组,多少行我不知道
b = a.reshape((-1, 3, 2))
print("修改后:")
print(b)

在这里插入图片描述
key:在数组的一开始,数方括号,个数即为维数,原数组为二维数组,修改的数组为3维数组

以上就是reshape的用法,后续可能还会补充,欢迎在评论区讨论哦!

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值