关于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的用法,后续可能还会补充,欢迎在评论区讨论哦!

猜你喜欢

转载自blog.csdn.net/weixin_45153969/article/details/131653369
今日推荐