簡體   English   中英

如何將最后一列(1d 數組)附加到 python 中的 2d numpy 數組?

[英]How to append a last column (1d array) to a 2d numpy array in python?

我有兩個數組:

import numpy as np
a = np.array([[1,2,3], [4,5,6]])
b = np.array([5, 6])

當我嘗試使用以下代碼將b附加到a作為a的最后一列時

 np.hstack([a, b])



it thows an error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in hstack
  File "C:\Users\utkal\anaconda3\envs\AIML\lib\site-packages\numpy\core\shape_base.py", line 345, in hstack
    return _nx.concatenate(arrs, 1)
  File "<__array_function__ internals>", line 6, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)

我希望最終的數組為:

1 2 3 5
4 5 6 6

你可以這樣做:

np.hstack((a,b.reshape(2,1)))
array([[1, 2, 3, 5],
       [4, 5, 6, 6]])

np.hstacknp.concatenate on axis=1 的快捷方式。 因此,它要求兩個數組具有相同的形狀,並且除了連接軸之外的所有維度都匹配。 在您的情況下,您需要二維數組和維度0匹配

所以你需要

np.hstack([a, b[:,None]])

Out[602]:
array([[1, 2, 3, 5],
       [4, 5, 6, 6]])

或者使用np.concatenate

np.concatenate([a, b[:,None]], axis=1)

Out[603]:
array([[1, 2, 3, 5],
       [4, 5, 6, 6]])

暫無
暫無

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

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