2024-09-26 18:07:14 发布
网友
我的数据帧的每一行都有一个字符串列表。我想计算列中字符串的唯一数量。我目前的方法很慢:
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
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) ) )))
我认为您需要由连接词和拆分词创建的集合长度:
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
例如,您可以使用下一个变体:
我认为您需要由连接词和拆分词创建的集合长度:
如果有使用集合理解的列表,谢谢@juanpa.arrivillaga:
相关问题 更多 >
编程相关推荐