Dave'o-Telephone Dave'o-Telephone - 6 months ago 38
Python Question

Counting groups in list

I'm trying to count the number of distinct groups of text labels in the list

in python. e.g

for i in blabla['Condition'].unique():
print i

the output of which is:

no1 med1 48h
no1 med1 72h
no1 med1 96h
no1 med1 120h
no2 med1 48h
no2 med1 72h
no2 med1 96h
no2 med1 120h
no1 med2 48h
no1 med2 72h
no1 med2 96h
no1 med2 120h

I want to count amount of times the repeat (i.e.
) occurs in the particular list
. In this case 3 times.


You could try:

>>> ids = set(' '.join(item.split()[:2])
...           for item in blabla['Condition'].unique()))
# set(['no2 med1', 'no1 med1', 'no1 med2'])
>>> len(ids)

That is, treat the first two words of each item as its identifier, and count the number of unique identifiers.

(It is necessary to convert the list item.split()[:2] back to a string using join, because lists cannot be used as set elements, which is required here to make them unique.)