performance - Python : break up dataframe (one row per entry in column, 而不是列中的多个条目)

标签 performance pandas python-3.4

我有一个问题的解决方案,但令我绝望的是有点慢,我正在寻求有关如何加快解决方案速度的建议(通过添加矢量化或其他聪明的方法)。我有一个如下所示的数据框:

toy = pd.DataFrame([[1,'cv','c,d,e'],[2,'search','a,b,c,d,e'],[3,'cv','d']],
                   columns=['id','ch','kw'])

输出是:

enter image description here

任务是将每个字符串中每个逗号分隔条目的 kw 列分解为一行(复制)。因此,我希望实现的是:

enter image description here

我的初步解决方案如下:

data = pd.DataFrame()
for x in toy.itertuples():
    id = x.id; ch = x.ch; keys = x.kw.split(",")
    data = data.append([[id, ch, x] for x in keys], ignore_index=True)
data.columns = ['id','ch','kw']

问题是:对于较大的数据帧来说速度很慢。我希望有人以前遇到过类似的问题,并且知道如何优化我的解决方案。如果这很重要的话,我正在使用 python 3.4.x 和 pandas 0.19+。

谢谢!

最佳答案

您可以使用str.split对于 list,然后获取 len对于长度

最后通过构造函数使用numpy.repeat创建新的DataFramenumpy.concatenate :

cols = toy.columns
splitted = toy['kw'].str.split(',')
l = splitted.str.len()

toy = pd.DataFrame({'id':np.repeat(toy['id'], l),
                    'ch':np.repeat(toy['ch'], l),
                    'kw':np.concatenate(splitted)})
toy = toy.reindex_axis(cols, axis=1)
print (toy)
   id      ch kw
0   1      cv  c
0   1      cv  d
0   1      cv  e
1   2  search  a
1   2  search  b
1   2  search  c
1   2  search  d
1   2  search  e
2   3      cv  d

关于performance - Python : break up dataframe (one row per entry in column, 而不是列中的多个条目),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44458434/

相关文章:

performance - JMeter 与研磨机?

ruby-on-rails - 我应该如何添加用户配置文件和隐私来设计?

python - Pandas 变频

python - DataFrame Python 中的数学求值字符串

python - Pandas :TypeError:在日期列上选择时, '>' 和 'int' 实例之间不支持 'str'

python - multiprocessing.Process 在哪里

performance - 在这个插入排序算法的分析中,求和是什么意思呢?

Python:一种优雅/有效的方法来评估二维索引上的函数?

python - 为什么我的python程序总是显示相反的 react

python - 如何格式化正则表达式