有誰知道 numpy 的替代品pd.factorize()?
我需要演算法的速度,并且不想使用 pandas 資料框。
例如,
test = np.array(['yo', 'whats', 'up', 'whats', 'up', 'yo'])
將回傳
pd.factorize(pd.Series(test))
array([0, 1, 2, 1, 2, 0])
uj5u.com熱心網友回復:
您可以
比較 1 到 ~33M 行,包含 52 個因素

uj5u.com熱心網友回復:
上面已經是一個很好的答案。下面選項 #2 的掛墻時間幾乎是一半:
import numpy as np
test = np.array(['yo', 'whats', 'up', 'whats', 'up', 'yo'])
選項#1:
%%time
x, y = np.unique(test, return_inverse=True)
y
輸出:
CPU times: user 103 μs, sys: 23 μs, total: 126 μs
Wall time: 110 μs
array([2, 1, 0, 1, 0, 2])
選項#2:
d={}
[d.setdefault(w, i) for i, w in enumerate(test)]
輸出:
CPU times: user 60 μs, sys: 1e 03 ns, total: 61 μs
Wall time: 64.1 μs
[0, 1, 2, 1, 2, 0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454656.html
