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

2024-06-16 10:41:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

需要输出:7

它也不会检查一个单词是否出现在两行或更多行中,这会使它变得更慢。这能以一种快速的方式完成吗? 谢谢


Tags: to数据方法字符串df列表数量party
2条回答

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

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

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

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

相关问题 更多 >