gpt4 book ai didi

python - 列表python中每个唯一元素的所有索引

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:45 25 4
gpt4 key购买 nike

我正在处理一个非常大的数据集(大约 7500 万个条目),我正在尝试大幅缩短运行我的代码所花费的时间(现在使用循环将需要几个天)并保持极低的内存使用率。

我有两个相同长度的 numpy 数组(clientsunits)。我的目标是获取第一个列表 (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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com