numpy.reshape()函数

时间:2020-02-23 14:42:21  来源:igfitidea点击:

什么是numpy.reshape()函数?

Python NumPy模块可用于对数据执行数学和科学运算。
NumPy模块以数组形式处理数据。

numpy.reshape()函数使用户可以更改元素所在数组的尺寸。
也就是说,我们可以使用reshape()函数将数据重塑为任意维度。

而且,它允许程序员更改在特定维度上结构化的元素数量。

现在,让我们在以下部分中重点介绍reshape()函数的语法。

reshape()函数的语法

看看下面的语法!

array.reshape(shape)

  • array —要重塑的数据结构(总是一个数组!)
  • shape —决定新数组维数的整数元组值

reshape()函数不会更改数组的元素。
它仅更改数组的尺寸,即架构/结构。

现在,让我们尝试通过一个示例使用reshape()函数来可视化尺寸的变化:

让我们考虑一个尺寸为1×6的数组arr = {1,2,3,4,5,6}。
该数组可以重新构建为以下形式:

3×2尺寸:

3×2尺寸

2×3尺寸:

2×3尺寸

6×1尺寸:

6×1尺寸

现在让我们通过一些示例来实现reshape()函数的概念,如下所示。

reshape()函数的示例

在以下示例中,我们使用numpy.array()函数创建了一个一维numpy数组。
此外,我们将数组的尺寸更改为2×2。

import numpy as np 

a = np.array([1, 2, 3,4])
print("Elements of the array before reshaping: \n", a) 

reshape = a.reshape(2,2) 
print("\n Array elements after reshaping: \n", reshape)

输出:

Elements of the array before reshaping: 
[1 2 3 4]

Array elements after reshaping: 
[[1 2]
[3 4]]

现在,我们创建了一个二维数组,并通过将-1作为reshape()函数的参数提供了将数组的尺寸更改为一维数组。

import numpy as np 
 
a = np.array([[1, 2, 3,4],[2,4,6,8]])
print("Elements of the array before reshaping: \n", a) 
 
reshape = a.reshape(-1) 
print("\n Array elements after reshaping: \n", reshape)

输出:

Elements of the array before reshaping: 
 [[1 2 3 4]
 [2 4 6 8]]

Array elements after reshaping: 
 [1 2 3 4 2 4 6 8]

其中我们使用numpy.arange()函数创建了一个数组。
然后,我们将数组的尺寸更改为2×3,即2行3列。

import numpy as np 
 
a = np.arange(6)
print("Elements of the array before reshaping: \n", a) 
 
reshape = a.reshape(2,3) 
print("\n Array elements after reshaping: \n", reshape)

输出:

Elements of the array before reshaping: 
 [0 1 2 3 4 5]

Array elements after reshaping: 
 [[0 1 2]
 [3 4 5]]