I have such a data frame:
id countries
01 [UK,UK,UK,US]
02 [US,US,US,US]
03 [FR,UK,CN,US]
I want to count how many countries exist for each id. Like the result should be like:
id countries counts
01 [UK,UK,UK,US] 2
02 [US,US,US,US] 1
03 [FR,UK,CN,US] 4
If values are list
s convert them to set
and get length
:
print (type(df.loc[0, 'countries']))
<class 'list'>
df['counts'] = df['countries'].apply(lambda x: len(set(x)))
print (df)
id countries counts
0 1 [UK, UK, UK, US] 2
1 2 [US, US, US, US] 1
2 3 [FR, UK, CN, US] 4
Or if values are strings
first remove []
and split:
print (type(df.loc[0, 'countries']))
<class 'str'>
df['counts'] = df['countries'].str.strip('[]').str.split(',').apply(lambda x: len(set(x)))
print (df)
id countries counts
0 1 [UK,UK,UK,US] 2
1 2 [US,US,US,US] 1
2 3 [FR,UK,CN,US] 4
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.