将numpy多维数组转换为一维数组有两种方法
- 使用reshape()函数,这个方法是间接法,利用reshape()函数的属性,间接的把二维数组转换为一维数组
- 使用flatten()函数, 推荐使用这个方法,这个方法是numpy自带的函数
import numpy as np
arr = np.arange(12).reshape(3, 4)
print(arr)
d_1 = arr.flatten()
print(d_1)
print("------------------------")
arr2 = arr.reshape(2, 2, 3)
print(arr2)
d_2 = arr2.flatten()
print(d_2)
输出:
D:\Anaconda3\envs\tensorflow\python.exe D:/PycharmProjects/untitled1/test/test1.py
[[ 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]
Process finished with exit code 0