0
点赞
收藏
分享

微信扫一扫

python/numpy辨析--reshape和resize的区别?有哪些函数可以改变数组的形状?

微笑沉默 2022-03-11 阅读 142

一、有那些函数可以改变数组的形状?

  • ndarray.flat
  • ndarray.flatten(order)
  • ndarray.ravel(order)
  • ndarray.resize(newshape,order)和numpy.resize(ndarray,newshape,order)
  • ndarray.reshape(newshape,order)和numpy.reshape(ndarray,newshape,order)

以下都是基于python3.8,numpy1.22。

二、resize和reshape的区别有哪些?

1.resize才可以改变形状的大小,reshape不能改变形状的大小。

这里指的形状大小指各个维度尺寸的相乘,比如原形状是(3,4),大小是12,如果用reshape()新形状可以是(1,12),(2,6),但不能是(6,4)。

如果使用ndarray.resize扩展形状大小,空白部分用第一个元素补全,如果使用numpy.resize()扩展形状大小,空白部分依次用原数据的从头到尾的顺序填充。

import numpy as np
arr = np.arange(12).reshape(3,4)

print(np.reshape(arr,(6,8)))
# ValueError: cannot reshape array of size 12 into shape (6,8)

print(np.resize(arr,(6,8)))
#  输出为▼▼▼
# [[ 0  1  2  3  4  5  6  7]
#  [ 8  9 10 11  0  1  2  3]
#  [ 4  5  6  7  8  9 10 11]
#  [ 0  1  2  3  4  5  6  7]
#  [ 8  9 10 11  0  1  2  3]
#  [ 4  5  6  7  8  9 10 11]]


# ------------以上是调用numpy函数,以下是调用ndarray属性-------------


import numpy as np
arr = np.arange(12).reshape(3,4)

arr.resize(4,3)
print(arr)
#  输出为▼▼▼
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]
arr1 = arr.copy()
arr1.resize(8, 3)
print(arr1)
#  输出为▼▼▼
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]
#  [ 0  0  0]
#  [ 0  0  0]
#  [ 0  0  0]
#  [ 0  0  0]]

print(arr.reshape(6,8))
# ValueError: cannot reshape array of size 12 into shape (6,8)

注意:对于ndarray.resize,如果涉及到改变形状大小,可能会报错【ValueError: cannot resize this array: it does not own its data】,这时把原数组进行一个拷贝(至少是浅拷贝,不能是引用),然后对拷贝的那一份进行ndarray.resize,就可以避免该错误了。

  • ndarray.resize(newshape,order)和numpy.resize(ndarray,newshape,order)
  • ndarray.reshape(newshape,order)和numpy.reshape(ndarray,newshape,order)

2.不管是ndarray.reshape还是numpy.reshape,都无法直接改变原数组,但是都可以通过返回值得到改变形状后的数组;只有ndarray.resize才能直接改变原数组,而对于numpy.resize也需要通过返回值得到改变形状后的数组;或许正是因为只有ndarray.resize才能直接改变原数组,所以也只有这一种用法没有返回值。

import numpy as np

arr = np.arange(12).reshape(2, 6)

print(np.resize(arr, (3, 4)))
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
print(arr)
# [[ 0  1  2  3  4  5]
#  [ 6  7  8  9 10 11]]

print(np.reshape(arr, (4, 3)))
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]
print(arr)
# [[ 0  1  2  3  4  5]
#  [ 6  7  8  9 10 11]]

print(arr.resize(3, 4))
# 输出None
print(arr)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

print(arr.reshape(4, 3))
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]
print(arr)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

print(np.arange(12).resize(2, 6))
# 输出None

三、参考来源

numpy 辨异(一) —— reshape 与 resize_https://space.bilibili.com/59807853-CSDN博客

Python——数组重组(flatten、flat、ravel、reshape、resize)_Haiyang_Duan-CSDN博客_python 数组flat

举报

相关推荐

0 条评论