numpy用整数逐步替换元素组

numpy用整数逐步替换元素组,第1张

numpy用整数逐步替换元素组

编辑:这并不总是有效:

>>> a,b,c = np.unique(data, return_index=True, return_inverse=True)>>> c # almost!!!array([1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 3, 3])>>> np.argsort(b)[c]array([0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3], dtype=int64)

但这确实有效:

def replace_groups(data):    a,b,c, = np.unique(data, True, True)    _, ret = np.unique(b[c], False, True)    return ret

并且比字典替换方法更快,对于较大的数据集,大约为33%:

def replace_groups_dict(data):    _, ind = np.unique(data, return_index=True)    unqs = data[np.sort(ind)]    data_id = dict(zip(unqs, np.arange(data.size)))    num = np.array([data_id[datum] for datum in data])    return numIn [7]: %timeit replace_groups_dict(lines100)10000 loops, best of 3: 68.8 us per loopIn [8]: %timeit replace_groups_dict(lines200)10000 loops, best of 3: 106 us per loopIn [9]: %timeit replace_groups_dict(lines)10 loops, best of 3: 32.1 ms per loopIn [10]: %timeit replace_groups(lines100)10000 loops, best of 3: 67.1 us per loopIn [11]: %timeit replace_groups(lines200)10000 loops, best of 3: 78.4 us per loopIn [12]: %timeit replace_groups(lines)10 loops, best of 3: 23.1 ms per loop


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5667831.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存