Skip to main content
 首页 » 编程设计

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

2024年10月17日8jackei

我正在处理一个非常大的数据集(大约 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 选项,因为这可能会加快速度(默认情况下条目将被排序,这对于巨大的数据集可能需要一些时间)。