![](/img/trans.png)
[英]Python group by and count distinct values in a column and create delimited list
[英]Count distinct values in Python list
我有一个如下的数据报
lable unigrams
ham [ive, searching, right, word, thank, breather, i, promise, wont]
spam [free, entry, 2, wkly, comp, win, fa, cup, final, tkts, 21st, may]
我想计算不同的/独特的火腿字母和垃圾邮件的字母。
我可以使用df.unigrams.nunique()
计算一列中的不同值。 我可以使用unigramCount = unigramCorpus.loc["ham", "unigrams"].count('ive')
给定的unigramCount = unigramCorpus.loc["ham", "unigrams"].count('ive')
在火腿中的出现unigramCount = unigramCorpus.loc["ham", "unigrams"].count('ive')
但是,如何计算给定列表中不同值的数量? 例如: ["ham", "spam"]
预期输出:火腿= 9垃圾邮件= 12
你需要:
df.assign(count = df.unigrams.apply(lambda x: len(set(x))))
label unigrams count
0 ham [ive, searching, right, word, thank, breather,...] 9
1 spam [free, entry, 2, wkly, comp, win, fa, cup, fin...] 12
使用np.unique
(在每个字母组合列表中仅计数不同的词,因此重复项将被忽略):
df['counts'] = df.apply(lambda x: len(np.unique(x['unigrams'])), axis=1)
print(df)
> label unigrams counts
0 ham [ive, searching, right, word, thank, breather,... 9
1 spam [free, entry, 2, wkly, comp, win, fa, cup, fin... 12
unigramCount = len(set(eval(unigramCorpus.loc [“ ham”,“ unigrams]])))
您的问题不是很清楚,但这可能有用:
df['count'] = df['unigrams'].map(lambda x: len(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.