簡體   English   中英

關於numpy的串聯,hstack,vstack函數?

[英]About numpy's concatenate, hstack, vstack functions?

看一些例子

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.concatenate((a,b), axis=0)) # [1,2,3,4,5,6]
print(np.hstack((a,b))) # [1,2,3,4,5,6]

print(np.vstack((a,b))) # [[1,2,3],[4,5,6]]
print(np.concatenate((a,b), axis=1)) # IndexError: axis 1 out of bounds [0, 1)

hstack的結果與沿axis = 0的連接相同,但api文檔說hstack =沿axis = 1的連接,請查看https://docs.scipy.org/doc/numpy-dev/reference/生成/numpy.hstack.html#numpy.hstack

並沿axis = 1串聯會引發IndexError,api文檔說hstack = concatenate沿axis = 0,請查看https://docs.scipy.org/doc/numpy-dev/reference/generation/numpy.vstack的.html#numpy.vstack

有人可以解釋嗎?有人可以解釋當ndarray的維數小於2並沿axis = 1並置時如何廣播嗎?

查看hstack的實際代碼:

arrs = [atleast_1d(_m) for _m in tup]
# As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
if arrs[0].ndim == 1:
    return _nx.concatenate(arrs, 0)
else:
    return _nx.concatenate(arrs, 1)

我在文檔中看不到關於axis=1任何內容。 它使用的術語是'stack them horizontally'

正如我一年前指出的那樣,如果沿軸第二個2D一維numpy數組的並置 ,則早期版本不會產生錯誤(如果軸太高)。 但是在1.12中我們得到一個錯誤。

有一個新的np.stack可以在需要的地方添加尺寸:

In [46]: np.stack((np.arange(3), np.arange(4,7)),axis=1)
Out[46]: 
array([[0, 4],
       [1, 5],
       [2, 6]])

基本函數是concatenate 各種stack函數以一種或另一種方式調整數組尺寸,然后進行concatenate 查看他們的代碼以查看詳細信息。 (我也總結了早期文章中的差異)。

np.hstack(tup)np.concatenate(tup, axis=1)確實是等效的,但是只有當tup包含的至少2維陣列。 這實際上是在vstack的文檔中vstack ,因此看起來只是一個疏忽,在hstack的文檔中也沒有hstack ; 它將用於將來的版本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM