从dataframe列创建集合和计数字典

w

我正在尝试从数据框列创建一组单词标记和一个单词计数字典。

df = pd.DataFrame({'a':[11,11,11,12,12,12], 'b':['The Effect','effective than','more','more','bark oola','a'], 'c': [1,2,3,5,6,9]})

我现在使用代码从“ b”列创建令牌

set(list(itertools.chain.from_iterable(df.b.str.split())))

这是最有效的方法吗?

如果我需要标记并在字典中计数(特定标记在列中出现的时间),该怎么办

通道3

您可以使用str.joinstr.split再转换到set

set(' '.join(df['b']).split())
# {'Effect', 'The', 'a', 'bark', 'effective', 'more', 'oola', 'than'}

您可以使用Series.explode然后Series.unique

df['b'].str.split().explode().unique()

# array(['The', 'Effect', 'effective', 'than', 'more', 'bark', 'oola', 'a'],
#       dtype=object)

timeits

标杆设置

s = pd.Series(['this', 'many strings', 'all are humans']*500)
s.append(['again some more random', 'foo bar']*500)
In [43]: %%timeit 
    ...: s.str.split().explode().unique() 
    ...:  
    ...:                                                                        
1.46 ms ± 4.66 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [44]: %%timeit 
    ...: set(list(itertools.chain.from_iterable(s.str.split()))) 
    ...:  
    ...:                                                                        
776 µs ± 4.98 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [49]: %timeit np.unique(s.str.split().explode())                             
2.48 ms ± 62.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [64]: %timeit set(' '.join(s).split())                                       
292 µs ± 20.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章