I have a 2D array:
expenses = np.array([['jim', 'sam', 'bill', 'sam'],[1,2,6,5]])
I want to know the total expenses for each unique person in a new array without hardcoding any names (real list is very long) so that I get an output like this:
totals = [['jim', 'sam', 'bill'],[1,7,6]]
Is there a way of doing this with a list or NumPy? I don't want to use Pandas for this.
Thanks in advance!
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)}
Another fun way to do this (without numpy) is using a 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())))
Output:
[['sam', 'jim', 'bill'], [7, 1, 6]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.