Python numpy 入門系列 14 數組操作(連接數組)


連接數組

函數 描述
concatenate 連接沿現有軸的數組序列
stack 沿着新的軸加入一系列數組。
hstack 水平堆疊序列中的數組(列方向)
vstack 豎直堆疊序列中的數組(行方向)

numpy.concatenate

numpy.concatenate 函數用於沿指定軸連接相同形狀的兩個或多個數組,格式如下:

numpy.concatenate((a1, a2, ...), axis)

參數說明:

  • a1, a2, ...:相同類型的數組
  • axis:沿着它連接數組的軸,默認為 0

實例

import numpy as np a = np.array([[1,2],[3,4]]) print ('第一個數組:') print (a) print ('\n') b = np.array([[5,6],[7,8]]) print ('第二個數組:') print (b) print ('\n') # 兩個數組的維度相同 print ('沿軸 0 連接兩個數組:') print (np.concatenate((a,b))) print ('\n') print ('沿軸 1 連接兩個數組:') print (np.concatenate((a,b),axis = 1))

輸出結果為:

第一個數組: [[1 2] [3 4]] 第二個數組: [[5 6] [7 8]] 沿軸 0 連接兩個數組: [[1 2] [3 4] [5 6] [7 8]] 沿軸 1 連接兩個數組: [[1 2 5 6] [3 4 7 8]]

numpy.stack

numpy.stack 函數用於沿新軸連接數組序列,格式如下:

numpy.stack(arrays, axis)

參數說明:

  • arrays相同形狀的數組序列
  • axis:返回數組中的軸,輸入數組沿着它來堆疊

實例

import numpy as np a = np.array([[1,2],[3,4]]) print ('第一個數組:') print (a) print ('\n') b = np.array([[5,6],[7,8]]) print ('第二個數組:') print (b) print ('\n') print ('沿軸 0 堆疊兩個數組:') print (np.stack((a,b),0)) print ('\n') print ('沿軸 1 堆疊兩個數組:') print (np.stack((a,b),1))

 輸出結果如下:

第一個數組: [[1 2] [3 4]] 第二個數組: [[5 6] [7 8]] 沿軸 0 堆疊兩個數組: [[[1 2] [3 4]] [[5 6] [7 8]]] 沿軸 1 堆疊兩個數組: [[[1 2] [5 6]] [[3 4] [7 8]]]

numpy.hstack

numpy.hstack 是 numpy.stack 函數的變體,它通過水平堆疊來生成數組。

實例

import numpy as np a = np.array([[1,2],[3,4]]) print ('第一個數組:') print (a) print ('\n') b = np.array([[5,6],[7,8]]) print ('第二個數組:') print (b) print ('\n') print ('水平堆疊:') c = np.hstack((a,b)) print (c) print ('\n')

 輸出結果如下:

第一個數組: [[1 2] [3 4]] 第二個數組: [[5 6] [7 8]] 水平堆疊: [[1 2 5 6] [3 4 7 8]]

numpy.vstack

numpy.vstack 是 numpy.stack 函數的變體,它通過垂直堆疊來生成數組。

實例

import numpy as np a = np.array([[1,2],[3,4]]) print ('第一個數組:') print (a) print ('\n') b = np.array([[5,6],[7,8]]) print ('第二個數組:') print (b) print ('\n') print ('豎直堆疊:') c = np.vstack((a,b)) print (c)

 輸出結果為:

第一個數組: [[1 2] [3 4]] 第二個數組: [[5 6] [7 8]] 豎直堆疊: [[1 2] [3 4] [5 6] [7 8]]

REF

https://www.cnblogs.com/mzct123/p/8659193.html  (numpy flatten ravel)
https://blog.csdn.net/weixin_43960668/article/details/114979389 (numpy flatten ravel)

https://www.runoob.com/numpy/numpy-array-manipulation.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM