我有这样一个数据框:
id countries
01 [UK,UK,UK,US]
02 [US,US,US,US]
03 [FR,UK,CN,US]
我想计算每个ID存在多少个国家/地区。喜欢的结果应该是:
id countries counts
01 [UK,UK,UK,US] 2
02 [US,US,US,US] 1
03 [FR,UK,CN,US] 4
答案 0 :(得分:2)
如果值为list
,则将其转换为set
并获取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
如果值为strings
,请先删除[]
并拆分:
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