Python--reshape

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

  1. numpy.arange(n).reshape(a, b) 依次生成n个自然数,并且以a行b列的数组形式显示
np.arange(16).reshape(2,8) #生成16个自然数,以2行8列的形式显示
# Out: 
# array([[ 0,  1,  2,  3,  4,  5,  6,  7],
#       [ 8,  9, 10, 11, 12, 13, 14, 15]])
  1. mat (or array).reshape(c, -1) 必须是矩阵格式或者数组格式,才能使用 .reshape(c, -1) 函数, 表示将此矩阵或者数组重组,以 c行d列的形式表示
arr.shape    # (a,b)
arr.reshape(m,-1) #改变维度为m行、d列 (-1表示列数自动计算,d= a*b /m )
arr.reshape(-1,m) #改变维度为d行、m列 (-1表示行数自动计算,d= a*b /m )

-1的作用就在此: 自动计算d:d=数组或者矩阵里面所有的元素个数/c, d必须是整数,不然报错)(reshape(-1, m)即列数固定,行数需要计算)

arr=np.arange(16).reshape(2,8)
arr
'''
out:
array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13, 14, 15]])
'''
 
arr.reshape(4,-1) #将arr变成4行的格式,列数自动计算的(c=4, d=16/4=4)
'''
out:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
''' 
arr.reshape(8,-1) #将arr变成8行的格式,列数自动计算的(c=8, d=16/8=2)
'''
out:
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15]])
''' 
arr.reshape(10,-1) #将arr变成10行的格式,列数自动计算的(c=10, d=16/10=1.6 != Int)
'''
out:
ValueError: cannot reshape array of size 16 into shape (10,newaxis)
'''
  1. numpy.arange(a,b,c) 从 数字a起, 步长为c, 到b结束,生成array
  2. numpy.arange(a,b,c).reshape(m,n) :将array的维度变为m 行 n列。
np.arange(1,12,2)#间隔2生成数组,范围在1到12之间
# Out: array([ 1,  3,  5,  7,  9, 11])
 
np.arange(1,12,2).reshape(3,2)
'''
Out: 
array([[ 1,  3],
       [ 5,  7],
       [ 9, 11]])
'''

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

import numpy as np
z=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
z.shape
Out[4]: (4, 4)
z.reshape(1,-1)
Out[5]: array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16]])

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

import numpy as np
z=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
z.shape
Out[4]: (4, 4)
z.reshape(1,-1)
Out[5]: array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16]])
z.shape
Out[6]: (4, 4)
z.reshape(2,-1)
Out[7]: 
array([[ 1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16]])

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

z.reshape(-1,1)
Out[8]: 
array([[ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5],
       [ 6],
       [ 7],
       [ 8],
       [ 9],
       [10],
       [11],
       [12],
       [13],
       [14],
       [15],
       [16]])

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

z.reshape(-1,2)
Out[9]: 
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10],
       [11, 12],
       [13, 14],
       [15, 16]])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值