Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the sums of unique values with respective occurrence count from a list in Python?

Tags:

python

With a list like this:

[1,1,1,2,2,3,3,3]

I would like to get the sums of each unique number [1,2,3] which is [3, 4, 9]. Using an approach from the related post How to get unique values with respective occurrence count from a list in Python? I'm able to get the count of the occurence of each uniqe number using:

L = [1,1,1,2,2,3,3,3]
uniq, counts = np.unique(L, return_counts=True)
counts

Which gives the output [3, 2, 3]. With this, I'm able to get what I'm looking for using a cumbersome approach with an enumerated For Loop and some rather cryptic conditions:

L = [1,1,1,2,2,3,3,3]
elements = [3,2,3]
    
sums = []
index = 0
for i, e in enumerate(elements):
    if i == 0:
        sums.append(sum(L[0:e]))
        index = index + e
    else:
        sums.append(sum(L[index:index + e]))
        index = index + e
print(sums)

Which gives the desired output [3, 4, 9]. Does anyone know if it's possible to do the same thing a bit more elegantly?

like image 701
vestland Avatar asked May 03 '21 21:05

vestland


People also ask

How do you count unique items in a list?

You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears.

How do you count the number of occurrences of all elements in a list in Python?

Method 4: Count occurrences of an element in a list Using countof() Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value.

Which syntax will you use to count number of unique values that occur in dataset or in a column?

read_csv() function in which pass the path and name of the dataset. Select the column in which you want to check or count the unique values. For finding unique values we are using unique() function provided by pandas and stored it in a variable, let named as 'unique_values'.


1 Answers

Since you are using Numpy, you can just multiply the results you already have from np.unique:

import numpy as np

L = [1,1,1,2,2,3,3,3]    
uniq, counts = np.unique(L, return_counts=True)

uniq * counts
# array([3, 4, 9])
like image 170
Mark Avatar answered Oct 13 '22 04:10

Mark