簡體   English   中英

使用 Numpy 在空數組中插入行

[英]Inserting rows in an empty array using Numpy

你好,我目前正在嘗試轉換這個數組

test=np.array([[0,0],[0,1],[1,1],[3,0]])

並使用曼哈頓距離將此數組轉換為此形狀

[0., 1., 2., 3.] 
[1., 0., 1., 4.]
[2., 1., 0., 3.,
[3., 4., 3., 0.]

代碼是這樣的

list_x=[]
newarray=np.array([])
length=len(test)
for i in range(length):
    for j in range(length):
        print('i=',i)
        print('j=',j)
        var=sum(abs(a-b) for a,b in zip(test[i],test[j]))
        list_x.append(var)
    newarray= np.append(newarray,list_x,axis = 0) 
    list_x=[]
    

但代碼的結果不斷給我這個:

array([0., 1., 2., 3., 1., 0., 1., 4., 2., 1., 0., 3., 3., 4., 3., 0.])

我的 np.append() 中是否存在阻止將其轉換為 4*4 shap 數組的問題?

您可以使用 scikit-learn 的manhattan_distances來獲取所有成對的曼哈頓距離,將上述簡化為單個函數調用:

from sklearn.metrics.pairwise import manhattan_distances

manhattan_distances(test)
array([[0., 1., 2., 3.],
       [1., 0., 1., 4.],
       [2., 1., 0., 3.],
       [3., 4., 3., 0.]])

如果您想使用 for 循環獲取距離,我建議您改用 python 列表。 為了得到一個嵌套列表,生成一個內部列表,其中包含一行與其他行的距離,並在每次迭代時將其附加到外部列表:

out=[]
for i in range(length):
    new_row = []
    for j in range(length):
        var=sum(abs(a-b) for a,b in zip(test[i],test[j]))
        new_row.append(var)
    out.append(new_row)

print(out)
# [[0, 1, 2, 3], [1, 0, 1, 4], [2, 1, 0, 3], [3, 4, 3, 0]]

另一種方法是使用 Scipy:

from scipy.spatial.distance import cdist
cdist(test,test,'cityblock')

輸出:

[[0. 1. 2. 3.]
 [1. 0. 1. 4.]
 [2. 1. 0. 3.]
 [3. 4. 3. 0.]]

比較

#@ehsan's solution
def m1(test):
  return cdist(test,test,'cityblock')

#@yatu's solution
def m2(test):
  return manhattan_distances(test)

in_ = [np.random.randint(0,10,(n,2)) for n in [10,100,1000,10000]]

對於大型陣列,它們似乎具有相似的性能,但對於較小的陣列(大約 1000 行), m1似乎更快。

在此處輸入圖片說明

暫無
暫無

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

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