Dave'o-Telephone Dave'o-Telephone - 19 days ago 6
Python Question

Counting groups in list

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

blabla
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.
48h
,
72h
,
96h
,
120h
) occurs in the particular list
blabla
. In this case 3 times.

Answer

You could try:

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

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.)