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?
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.
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.
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'.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With