pandas 系列中列表的有效串联 [英] efficient concatenation of lists in pandas series
本文介绍了 pandas 系列中列表的有效串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下系列文章:
s = pd.Series([['a', 'b'], ['c', 'd'], ['f', 'g']])
>>> s
0 [a, b]
1 [c, d]
2 [f, g]
dtype: object
最简单(最好是向量化)的方法来串联系列中的所有列表,这样我得到:
what is the easiest - preferably vectorized - way to concatenate all lists in the series, so that I get:
l = ['a', 'b', 'c', 'd', 'f', 'g']
谢谢!
推荐答案
嵌套列表理解应该更快.
A nested list comprehension should be much faster.
>>> [element for list_ in s for element in list_]
['a', 'b', 'c', 'd', 'f', 'g']
>>> %timeit -n 100000 [element for list_ in s for element in list_]
100000 loops, best of 3: 5.2 µs per loop
>>> %timeit -n 100000 s.sum()
100000 loops, best of 3: 50.7 µs per loop
直接访问列表的值甚至更快.
Directly accessing the values of the list is even faster.
>>> %timeit -n 100000 [element for list_ in s.values for element in list_]
100000 loops, best of 3: 2.77 µs per loop
这篇关于 pandas 系列中列表的有效串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文