Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Performance Python:分解数据帧(列中每个条目一行,而不是列中的多个条目)_Performance_Pandas_Python 3.4 - Fatal编程技术网

Performance Python:分解数据帧(列中每个条目一行,而不是列中的多个条目)

Performance Python:分解数据帧(列中每个条目一行,而不是列中的多个条目),performance,pandas,python-3.4,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']) 输出为: 任务是将kw列拆分为每个字符串中每个逗号分隔的条目的一(复制)行。因此,我希望达到的目标

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

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

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

我的初步解决方案如下:

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']
问题是:对于较大的数据帧,它的速度很慢。我希望有人以前遇到过类似的问题,并且知道如何优化我的解决方案。我正在使用Python3.4.x和pandas 0.19+,如果这很重要的话

谢谢大家!

您可以使用for
列表
s,然后获取for
长度

最后通过
constructor
和创建新的
DataFrame


谢谢,也非常快。我会立即尝试(我会在完成精神检查后立即接受您的回答)。再次感谢!
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