我正在处理一个非常大的数据集(大约 7500 万个条目),并且我正在尝试大幅缩短运行代码所需的时间(现在有一个循环,需要几个小时)天)并保持内存使用量极低。
我有两个长度相同的 numpy 数组(clients
和 units
)。我的目标是获取第一个列表 (clients
) 中出现值的每个索引的列表,然后找到第二个列表中每个索引处的条目总和。
这是我尝试过的(np
是之前导入的numpy库)
# create a list of each value that appears in clients
unq = np.unique(clients)
arr = np.zeros(len(unq))
tmp = np.arange(len(clients))
# for each unique value i in clients
for i in range(len(unq)) :
#create a list inds of all the indices that i occurs in clients
inds = tmp[clients==unq[i]]
# add the sum of all the elements in units at the indices inds to a list
arr[i] = sum(units[inds])
有谁知道一种方法可以让我找到这些总和,而无需循环遍历 unq
中的每个元素?
最佳答案
与 Pandas ,这可以使用 grouby()
轻松完成功能:
import pandas as pd
# some fake data
df = pd.DataFrame({'clients': ['a', 'b', 'a', 'a'], 'units': [1, 1, 1, 1]})
print df.groupby(['clients'], sort=False).sum()
这会为您提供所需的输出:
units
clients
a 3
b 1
我使用 sort=False
选项,因为这可能会导致加速(默认情况下,条目将被排序,这对于巨大的数据集可能需要一些时间)。
关于python - python 列表中每个唯一元素的所有索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38126477/