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]
方法二:使用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]]