python將二維數(shù)組升為一維數(shù)組或二維降為一維方法實例
1. 二維(多維)數(shù)組降為一維數(shù)組
方法1: reshape()+concatenate 函數(shù),
這個方法是間接法,利用 reshape() 函數(shù)的屬性,間接的把二維數(shù)組轉(zhuǎn)換為一維數(shù)組;
import numpy as np mulArrays = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(list(np.concatenate(mulArrays.reshape((-1, 1), order="F")))) Out[1]: [1, 4, 7, 2, 5, 8, 3, 6, 9]
方法2: flatten() 函數(shù),
推薦使用這個方法,這個方法是 numpy 自帶的函數(shù);
# coding = utf-8 import numpy as np import random # 把二維數(shù)組轉(zhuǎn)換為一維數(shù)組 t1 = np.arange(12) print(t1) Out[0]: [ 0 1 2 3 4 5 6 7 8 9 10 11] t2 = t1.reshape(3, 4) print(t2) t3 = t2.reshape(t2.shape[0] * t2.shape[1], ) print(t3) t4 = t2.flatten() print(t4)
運行效果如下圖所示:

可以看到這兩種方式都可以把二維數(shù)組轉(zhuǎn)換為一維數(shù)組,但是推薦使用 flatten() 函數(shù),該方法也可以將多維數(shù)組轉(zhuǎn)換為一維數(shù)組。
import numpy as np a = np.array([[1, 2], [3, 4], [9, 8]]) b = a.flatten() print(b)
輸出結(jié)果為:[1, 2, 3, 4, 9, 8]
方法3: itertools.chain
import numpy as np a = np.array([[1, 2], [3, 4], [9, 8]]) # 使用庫函數(shù) from itertools import chain a_a = list(chain.from_iterable(a)) print(a_a)
輸出結(jié)果為:[1, 2, 3, 4, 9, 8]
方法4: sum()
mulArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(sum(mulArrays, [])) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
方法5:operator.add + reduce
import operator from functools import reduce mulArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(reduce(operator.add, mulArrays)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
方法6:列表推導(dǎo)式
mulArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print([i for arr in mulArrays for i in arr]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
2. 一維數(shù)組升為 2 維數(shù)組
方法1:numpy 方法
利用函數(shù) reshape 或者是 resize。
使用 reshape 的時候需要注意 reshape 的結(jié)果不改變,因此適用于還要用到原數(shù)組的情況。
使用 resize 會改變原數(shù)組,因此適用于一定需要修改后的結(jié)果為值的情況。
import numpy as np x = np.arange(20) # 生成數(shù)組 print(x) result = x.reshape((4, 5)) # 將一維數(shù)組變成4行5列 原數(shù)組不會被修改或者覆蓋 x.resize((2, 10)) # 覆蓋原來的數(shù)據(jù)將新的結(jié)果給原來的數(shù)組 print(x)
輸出結(jié)果
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]]
總結(jié)
到此這篇關(guān)于python將二維數(shù)組升為一維數(shù)組或二維降為一維的文章就介紹到這了,更多相關(guān)python二維數(shù)組升為一維數(shù)組內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用tf.keras.MaxPooling1D出現(xiàn)錯誤問題及解決
這篇文章主要介紹了使用tf.keras.MaxPooling1D出現(xiàn)錯誤問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
pyecharts實現(xiàn)數(shù)據(jù)可視化
這篇文章主要介紹了pyecharts實現(xiàn)數(shù)據(jù)可視化,pyecharts 是百度開源的,適用于數(shù)據(jù)可視化的工具,配置靈活,展示圖表相對美觀,順滑,下面更多詳細內(nèi)容,需要的小伙伴可以參考一下2022-03-03
使用Fastapi打包exe后無限啟動導(dǎo)致死機的解決辦法
將 fastapi 服務(wù)打包成 exe 后雙擊執(zhí)行,命令行中不斷創(chuàng)建服務(wù)導(dǎo)致cpu吃滿,最后死機,所以本文給大家介紹了Fastapi打包exe后無限啟動導(dǎo)致死機的解決辦法,需要的朋友可以參考下2024-03-03

