Python-NumPy库中reshape()的用法

在NumPy中ndarray.ndim可以返回这个数组的维数,等于秩(即轴的数量)。reshape()函数可以将数组变形重构,调整数组各维数的大小。

 但是在使用reshape()时要注意数据量是否能转换成我们所需要的行列数。如16的话分成3行6列会报错。

reshape()常用的几种形式,以一下代码为例:

(1)转换成m行n列:reshape(m,n)

import numpy as np
arr = np.array([0,1,2,3,4,5,6,7])
#显示数组arr的秩
print('原秩为:',arr.ndim)
#使用reshape()改成2行4列
arr3D = arr.reshape(2,4)
print('改成2行4列为:',arr3D)
print('改成2行4列后的秩为:',arr3D.ndim)
#使用reshape()改成4行2列
print('改成4行2列为:',arr3D.reshape(4,2))
print('改成4行2列的秩为:',arr3D.ndim)

'''
输出结果为:
原秩为: 1
改成2行4列为: [[0 1 2 3]
 [4 5 6 7]]
改成2行4列后的秩为: 2
改成4行2列为: [[0 1]
 [2 3]
 [4 5]
 [6 7]]
改成4行2列的秩为: 2
'''

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

import numpy as np
arr = np.array([0,1,2,3,4,5,6,7])
#显示数组arr的秩
print('原秩为:',arr.ndim)
#使用reshape()转换成8行1列
print(arr3D.reshape(8,-1))
print('改后的秩为:',arr3)


'''
输出结果为:
[[0]
 [1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]]
改后的秩为: 2
'''

(3)转换成1行n列:reshape(-1,n)

import numpy as np
arr = np.array([0,1,2,3,4,5,6,7])
#显示数组arr的秩
print('原秩为:',arr.ndim)
print('原数组:',arr)
#使用reshape()转换成1行8列
arr3D = arr.reshape(-1,8)
print('改后数组:',arr3D)
print('改后的秩为:',arr3D.ndim)


'''
输出结果:
原秩为: 1
原数组: [0 1 2 3 4 5 6 7]
改后数组: [[0 1 2 3 4 5 6 7]]
改后的秩为: 2
'''

reshape(-1,8)中的-1,是模糊控制,负数可以为任何数。这里是固定8列,多少行系统根据元素数量自动计算好。若出现了无法整除的情况,系统会报错。

(4)转换成2层2行2列:reshape(a,b,c),变成三维数组,因为输出的秩为3

import numpy as np
arr = np.array([0,1,2,3,4,5,6,7])
#显示数组arr的秩
print('原秩为:',arr.ndim)
print('原数组:',arr)
#使用reshape()转换成2层2行2列
arr3D = arr.reshape(2,2,2)
print('改后数组为:')
print(arr3D)
print('改后的秩为:',arr3D.ndim)


'''
原秩为: 1
原数组: [0 1 2 3 4 5 6 7]
改后数组为:
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]
改后的秩为: 3
'''

未完持续补充中.....

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值