簡體   English   中英

什么是Excel的SUMIF函數的Python列表或等效的NumPy?

[英]What is the Python list or NumPy equivalent of Excel's SUMIF function?

我有一個二維數組:

expenses = np.array([['jim', 'sam', 'bill', 'sam'],[1,2,6,5]])

我想知道一個新數組中每個唯一人員的總支出,而無需對任何名稱進行硬編碼(實際列表很長),這樣我就得到了這樣的輸出:

totals = [['jim', 'sam', 'bill'],[1,7,6]]

有沒有辦法使用列表或NumPy? 我不想為此使用熊貓。

提前致謝!

names = np.asarray(['jim', 'sam', 'bill', 'sam'])
values = np.asarray([1, 2, 6, 5])
result = {name: values[names == name].sum() for name in np.unique(names)}

另一個有趣的方法(沒有numpy)是使用Counter

from collections import Counter
names = ['jim', 'sam', 'bill', 'sam']
counts = [1,2,6,5]
c = Counter()
for name, count in zip(names,counts):
    c[name] += count
# Remapping of dict to list of lists
list(map(list, zip(*c.items())))

輸出:

[['sam', 'jim', 'bill'], [7, 1, 6]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM