我有一個數據集表示有向圖。第一列是源節點,第二列是目標節點,我們可以忽略第三列(本質上是權重)。例如:有效計數numpy列中的重複值並追加計數
0 1 3
0 13 1
0 37 1
0 51 1
0 438481 1
1 0 3
1 4 354
1 10 2602
1 11 2689
1 12 1
1 18 345
1 19 311
1 23 1
1 24 366
...
我想要做的是追加每個節點的出度。例如,如果我剛添加的出度節點0,我會:
0 1 3 5
0 13 1 5
0 37 1 5
0 51 1 5
0 438481 1 5
1 0 3
...
我有一些代碼,這樣做,但它是非常緩慢的,因爲我用的是for
循環:
import numpy as np
def save_degrees(X):
new_col = np.zeros(X.shape[0], dtype=np.int)
X = np.column_stack((X, new_col))
node_ids, degrees = np.unique(X[:, 0], return_counts=True)
# This is the slow part.
for node_id, deg in zip(node_ids, degrees):
indices = X[:, 0] == node_id
X[:, -1][indices] = deg
return X
train_X = np.load('data/train_X.npy')
train_X = save_degrees(train_X)
np.save('data/train_X_degrees.npy', train_X)
有沒有更有效的方式來建立這個數據結構?
第一列是否總是排序? – Divakar
我相信它是排序的,但我可以根據需要對其進行排序。 – gwg
已發佈的解決方案是否適合您? – Divakar