Python的reshape的用法

 

请参考:https://blog.csdn.net/qq_29831163/article/details/90112000#reshape(1%2C-1)%E8%BD%AC%E5%8C%96%E6%88%901%E8%A1%8C%EF%BC%9A

numpy中reshape函数的三种常见相关用法 

  reshape(1,-1)转化成1行: 

  reshape(2,-1)转换成两行: 

  reshape(-1,1)转换成1列: 

  reshape(-1,2)转化成两列

numpy中reshape函数的三种常见相关用法

  • numpy.arange(n).reshape(a, b)    依次生成n个自然数,并且以a行b列的数组形式显示

np.arange(16).reshape(2,8) #生成16个自然数,以2行8列的形式显示

import numpy as np


arr = np.arange(16).reshape(2,8)
print(arr)

结果:  

[[ 0 1 2 3 4 5 6 7]
[ 8 9 10 11 12 13 14 15]]

  • mat (or array).reshape(c, -1)     必须是矩阵格式或者数组格式,才能使用 .reshape(c, -1) 函数, 表示将此矩阵或者数组重组,以 c行d列的形式表示

arr.reshape(4,-1) #将arr变成4行的格式,列数自动计算的(c=4, d=16/4=4)

#将arr变成4行的格式,列数自动计算的(c=4, d=16/4=4)
arr2 = arr.reshape((4,-1))
print(arr2)

结果:

[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

#reshape(2,-1)转换成两行:
arr5 = arr.reshape((2,-1))
print(arr5)

结果:

[[ 0 1 2 3 4 5 6 7]
[ 8 9 10 11 12 13 14 15]]

#reshape(-1,2)转化成两列:
arr6 = arr.reshape((-1,2))
print(arr6)

结果:

[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]]

  • numpy.arange(a,b,c)    从 数字a起, 步长为c, 到b结束,生成array
  • numpy.arange(a,b,c).reshape(m,n)  :将array的维度变为m 行 n列。

#reshape(1,-1)转化成1行:
arr3 = arr.reshape(1,-1)
print(arr3)

结果:[[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]]

#reshape(-1,1)转化成1列:
arr4 = arr.reshape(-1,1)
print(arr4)

结果:

[[ 0]
[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]
[11]
[12]
[13]
[14]
[15]]

原文地址:https://www.cnblogs.com/gaojr/p/12176944.html