繁体   English   中英

计算一列列表中唯一元素的有效方法?

[英]Efficient way to count unique elements in a column of lists?

我的 dataframe 的每一行都有一个字符串列表。 我想计算列中唯一的字符串数。 我目前的方法很慢:

              words
0  we like to party
1  can can dance
2  yes we can
...

df["words"].apply(lambda x: len(np.unique(x, return_counts=True)[1]))

通缉 output: 7

它也不会检查一个单词是否出现在 2 行或更多行中,这会使它变得更慢。 这可以快速完成吗? 谢谢!

我认为您需要通过连接和拆分单词创建的集合长度:

a = len(set(' '.join(df['words']).split()))
print (a)
7

如果有列表使用集合理解,谢谢@juanpa.arrivillaga:

print (df)
                   words
0  [we, like, to, party]
1      [can, can, dance]
2         [yes, we, can]


a = len({y for x in df['words'] for y in x})
print (a)
7

您可以使用例如下一个变体:

from itertools import chain
from operator import methodcaller

import pandas as pd

df = pd.DataFrame({
    "words": [
        "we like to party",
        "can can dance",
        "yes we can"
    ]
})

print(len(set(
    chain.from_iterable(
        map(methodcaller("split", " "), df.words.values)
    )
)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM