簡體   English   中英

Numpy 連接給出錯誤:軸 1 超出維度 1 數組的范圍

[英]Numpy concatenate giving error: axis 1 is out of bounds for array of dimension 1

尺寸似乎可以解決,但它仍然在抱怨(血壓升高):

x = np.array([1,2,3,4])
y = np.array([5,6,7,8])
m = np.array([9,10])
pointsx = np.concatenate((x,[m[0]]), axis=0)
pointsy = np.concatenate((y,[m[1]]), axis=0)
points = np.concatenate((pointsx.T,pointsy.T), axis=1)

可能有兩種解決方案:

(1) 使用 reshape() 改變一維向量在這里,如果 pointsx 和 pointsy 是一維向量並轉置它而不是使用.T (適用於更高維度)

import numpy as np
x = np.array([1,2,3,4])
y = np.array([5,6,7,8])
m = np.array([9,10])
pointsx = np.concatenate((x,[m[0]]), axis=0)
pointsy = np.concatenate((y,[m[1]]), axis=0)

points = np.concatenate((pointsx.reshape(-1,1),pointsy.reshape(-1,1)), axis=1)
print(points)

假設如果 pointsx = [1,2,3,4] 那么 pointsx.reshape(-1,1) 會將其轉換為

[[1]
 [2]
 [3]
 [4]
 [9]]

(2) 將一維向量轉換為矩陣,然后使用轉置。

import numpy as np
x = np.array([1,2,3,4])
y = np.array([5,6,7,8])
m = np.array([9,10])
pointsx = np.concatenate((x,[m[0]]), axis=0)
pointsy = np.concatenate((y,[m[1]]), axis=0)

points = np.concatenate((np.matrix(pointsx).T,np.matrix(pointsy).T), axis=1)
print(points)

您正在嘗試沿其軸 1(第二軸)連接一維數組,這是非法的。 要解決此問題,您需要將其重塑為 5x1 數組,然后將它們連接起來。 像這樣:

x = np.array([1,2,3,4])
y = np.array([5,6,7,8])
m = np.array([9,10])
pointsx = np.concatenate((x,[m[0]]), axis=0)
pointsy = np.concatenate((y,[m[1]]), axis=0)
pointsx = pointsx.reshape((-1, 1))
pointsy = pointsy.reshape((-1, 1))
points = np.concatenate((pointsx, pointsy), axis=1)

-1 只是告訴 Numpy 自己計算出該維度的長度,以便解決方案是通用的,並且不僅僅適用於長度為 5 的數組。

暫無
暫無

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

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