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

Python 在列表列中计算唯一元素的有效方法?,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,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])) 需要输出:7 它也不会检查一个单词是否出现在两行或更多行中,这会使它变得更慢。这能以一种快速的方式

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

              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

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

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

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

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

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

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

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

yoiu可以添加一些数据样本、2-3行和预期输出吗?或者需要
df[“words”]。应用(lambda x:len(set(x))
?@anInputName那么您需要单词唯一编号还是句子唯一编号?@dukkee一个单词唯一number@anInputName不用担心,几分钟后我会给你写一个解决方案:)yoiu可以添加一些数据样本吗,2-3行和预期输出?或需要
df[“words”]。应用(lambda x:len(set(x))
?@anInputName那么您需要单词唯一编号还是句子唯一编号?@dukkee一个单词唯一number@anInputName不用担心,几分钟后我会给你写一个解决方案:)