我有一個重復值陣列,用于將資料點與某個 ID 匹配。如何以矢量化方式將 ID 替換為計數索引值?
考慮以下最小示例:
import numpy as np
n_samples = 10
ids = np.random.randint(0,500, n_samples)
lengths = np.random.randint(1,5, n_samples)
x = np.repeat(ids, lengths)
print(x)
輸出:
[129 129 129 129 173 173 173 207 207 5 430 147 143 256 256 256 256 230 230 68]
所需的解決方案:
indices = np.arange(n_samples)
y = np.repeat(indices, lengths)
print(y)
輸出:
[0 0 0 0 1 1 1 2 2 3 4 5 6 7 7 7 7 8 8 9]
但是,在實際代碼中,我無權訪問 和 之類的變數ids,lengths而只能訪問x.
中的值是什么并不重要x,我只想要一個陣列,其中包含與中重復相同數量的整數x。
我可以使用 for-loops 或 提出解決方案np.unique,但對于我的用例來說,兩者都太慢了。
有沒有人想到一個快速演算法,它接受一個陣列x并回傳一個陣列y?
uj5u.com熱心網友回復:
你可以做:
y = np.r_[False, x[1:] != x[:-1]].cumsum()
或者少一個臨時陣列:
y = np.empty(len(x), int)
y[0] = 0
np.cumsum(x[1:] != x[:-1], out=y[1:])
print(y)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/461736.html
