📜  Python|将 2d numpy 数组展平为 1d 数组

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

Python|将 2d numpy 数组展平为 1d 数组

给定一个 2d numpy 数组,任务是将 2d numpy 数组展平为 1d 数组。以下是解决任务的一些方法。

方法 #1:使用 np.flatten()

# Python code to demonstrate
# flattening a 2d numpy array
# into 1d array
  
import numpy as np
  
ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])
  
# printing initial arrays
print("initial array", str(ini_array1))
  
# Multiplying arrays
result = ini_array1.flatten()
  
# printing result
print("New resulting array: ", result)
输出:
initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [1 2 3 2 4 5 1 2 3]


方法 #2:使用 np.ravel()

# Python code to demonstrate
# flattening a 2d numpy array
# into 1d array
  
import numpy as np
  
ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])
  
# printing initial arrays
print("initial array", str(ini_array1))
  
# Multiplying arrays
result = ini_array1.ravel()
  
# printing result
print("New resulting array: ", result)
输出:
initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [1 2 3 2 4 5 1 2 3]


方法 #3:使用 np.reshape()

# Python code to demonstrate
# flattening a 2d numpy array
# into 1d array
  
import numpy as np
  
ini_array1 = np.array([[1, 2, 3], [2, 4, 5], [1, 2, 3]])
  
# printing initial arrays
print("initial array", str(ini_array1))
  
# Multiplying arrays
result = ini_array1.reshape([1, 9])
  
# printing result
print("New resulting array: ", result)
输出:
initial array [[1 2 3]
 [2 4 5]
 [1 2 3]]
New resulting array:  [[1 2 3 2 4 5 1 2 3]]