3

我有两个 numpy 数组,users并且dat. 对于每个用户,users我需要找到与用户相关的数据dat并计算唯一值的数量。我需要处理一个案例 wherelen(users)=200000len(dat)=2800000. 目前我没有利用dat排序的事实,使方法非常慢。我该怎么做呢?

值“其他”dat仅表明结构化数组中也将存在其他值。

import numpy as np

users = np.array([111, 222, 333])
info = np.zeros(len(users))
dt = [('id', np.int32), ('group', np.int16), ('other', np.float)]
dat = np.array([(111, 1, 0.0), (111, 3, 0.0), (111, 2, 0.0), (111, 1, 0.0),
               (222, 1, 0.0), (222, 1, 0.0), (222, 4, 0.0),
               (333, 2, 0.0), (333, 1, 0.0), (333, 2, 0.0)],
               dtype=dt)

for i, u in enumerate(users):
    u_dat = dat[np.in1d(dat['id'], u)]
    uniq = set(u_dat['group'])
    info[i] = int(len(uniq))

print info
4

1 回答 1

2

如果您想从 numpy 的矢量化中获利,那么如果您可以事先删除所有重复项,那将有很大帮助dat。然后,您可以通过两次调用找到值的第一次和最后一次出现searchsorted

dat_unq = np.unique(dat)
first = dat_unq['id'].searchsorted(users, side='left')
last =  dat_unq['id'].searchsorted(users, side='right')
info = last - first

仅当您要在dat. 如果它是一个较小的分数,您仍然可以使用两个调用来searchsorted确定要调用哪些切片unique

info = np.empty_like(users, dtype=np.intp)
first = dat['id'].searchsorted(users, side='left')
last =  dat['id'].searchsorted(users, side='right')
for idx, (start, stop) in enumerate(zip(first, last)):
    info[idx] = len(np.unique(dat[start:stop]))
于 2015-08-30T21:52:09.117 回答