📌  相关文章
📜  将一维数组转换为二维 Numpy 数组

📅  最后修改于: 2022-05-13 01:55:51.445000             🧑  作者: Mango

将一维数组转换为二维 Numpy 数组

Numpy是一个Python包,由多维数组对象和一组操作或例程组成,用于对数组进行各种操作和处理数组。该包包含一个名为numpy.reshape的函数,该函数用于将一维数组转换为所需维度 (nxm) 的二维数组。该函数给出了一个新的所需形状,而不会改变一维数组的数据。

示例 1:

Python3
import numpy as np
# 1-D array having elements [1 2 3 4 5 6 7 8]
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
  
# Print the 1-D array
print ('Before reshaping:')
print (arr)
print ('\n')
  
# Now we can convert this 1-D array into 2-D in two ways
  
# 1. having dimension 4 x 2
arr1 = arr.reshape(4, 2)
print ('After reshaping having dimension 4x2:')
print (arr1)
print ('\n')
  
# 2. having dimension 2 x 4
arr2 = arr.reshape(2, 4)
print ('After reshaping having dimension 2x4:')
print (arr2)
print ('\n')


Python3
import numpy as np
# 1-D array having elements [1 2 3 4 5 6 7 8]
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
  
# Print the 1-D array
print('Before reshaping:')
print(arr)
print('\n')
  
# let us try to convert into 2-D array having dimension 3x3
arr1 = arr.reshape(3, 3)
print('After reshaping having dimension 3x3:')
print(arr1)
print('\n')


Python3
import numpy as np
# 1-D array having elements [1 2 3 4 5 6 7 8]
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
  
# Print the 1-D array
print('Before reshaping:')
print(arr)
print('\n')
  
  
arr1 = arr.reshape(2, 2, -1)
print('After reshaping:')
print(arr1)
print('\n')


输出:

Before reshaping:
[1 2 3 4 5 6 7 8]
After reshaping having dimension 4x2:
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
After reshaping having dimension 2x4:
[[1 2 3 4]
 [5 6 7 8]]

示例 2:让我们看到一个重要的观察结果,即我们是否可以将一维数组重塑为任何二维数组。

蟒蛇3

import numpy as np
# 1-D array having elements [1 2 3 4 5 6 7 8]
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
  
# Print the 1-D array
print('Before reshaping:')
print(arr)
print('\n')
  
# let us try to convert into 2-D array having dimension 3x3
arr1 = arr.reshape(3, 3)
print('After reshaping having dimension 3x3:')
print(arr1)
print('\n')

输出:

这得出结论,元素的数量应该等于维度的乘积,即 3×3=9 但总元素 = 8;

示例 3:另一个示例是我们可以使用 reshape 方法,而无需指定其中一个维度的确切数量。只需传递 -1 作为值,NumPy 将计算数字。

蟒蛇3

import numpy as np
# 1-D array having elements [1 2 3 4 5 6 7 8]
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
  
# Print the 1-D array
print('Before reshaping:')
print(arr)
print('\n')
  
  
arr1 = arr.reshape(2, 2, -1)
print('After reshaping:')
print(arr1)
print('\n')

输出:

Before reshaping:
[1 2 3 4 5 6 7 8]
After reshaping:
[[[1 2]
 [3 4]]
[[5 6]
 [7 8]]]