【问题标题】:how to speed-up a very slow pandas apply function?如何加快非常慢的熊猫应用功能?
【发布时间】:2016-03-17 06:04:56
【问题描述】:

我有一个非常大的 pandas 数据集,有时我需要使用以下函数

def proc_trader(data):
    data['_seq'] = np.nan
    # make every ending of a roundtrip with its index
    data.ix[data.cumq == 0,'tag'] = np.arange(1, (data.cumq == 0).sum() + 1)
    # backfill the roundtrip index until previous roundtrip;
    # then fill the rest with 0s (roundtrip incomplete for most recent trades)
    data['_seq'] =data['tag'].fillna(method = 'bfill').fillna(0)
    return data['_seq']
    # btw, why on earth this function returns a dataframe instead of the series `data['_seq']`??

我使用应用

reshaped['_spell']=reshaped.groupby(['trader','stock'])[['cumq']].apply(proc_trader)

显然,我无法在此处共享数据,但您是否发现我的代码存在瓶颈?会不会是arange 的事情?数据中有很多name-productid组合。

最小的工作示例:

import pandas as pd
import numpy as np

reshaped= pd.DataFrame({'trader' : ['a','a','a','a','a','a','a'],'stock' : ['a','a','a','a','a','a','b'], 'day' :[0,1,2,4,5,10,1],'delta':[10,-10,15,-10,-5,5,0] ,'out': [1,1,2,2,2,0,1]})


reshaped.sort_values(by=['trader', 'stock','day'], inplace=True)
reshaped['cumq']=reshaped.groupby(['trader', 'stock']).delta.transform('cumsum')
reshaped['_spell']=reshaped.groupby(['trader','stock'])[['cumq']].apply(proc_trader).reset_index()['_seq']

【问题讨论】:

  • 您是否尝试过对代码进行行分析?
  • 有一个图书馆,而且工作得很好,看看吧!我会看一下,但它可能与数据有关。 github.com/rkern/line_profiler
  • 如果我必须打赌,我会说这可能是 .ix 索引和分配,但同样,如果没有看到分析结果,很难说
  • 你的代码给了我TypeError: incompatible index of inserted column with frame index。有什么遗漏吗?
  • 这里也一样,TypeError

标签: python performance pandas


【解决方案1】:

这里没什么特别的,只是在几个地方进行了调整。真的没有必要放一个函数,所以我没有。在这个微小的样本数据上,它的速度大约是原始数据的两倍。

reshaped.sort_values(by=['trader', 'stock','day'], inplace=True)
reshaped['cumq']=reshaped.groupby(['trader', 'stock']).delta.cumsum()
reshaped.loc[ reshaped.cumq == 0, '_spell' ] = 1
reshaped['_spell'] = reshaped.groupby(['trader','stock'])['_spell'].cumsum()
reshaped['_spell'] = reshaped.groupby(['trader','stock'])['_spell'].bfill().fillna(0)

结果:

   day  delta  out stock trader  cumq  _spell
0    0     10    1     a      a    10     1.0
1    1    -10    1     a      a     0     1.0
2    2     15    2     a      a    15     2.0
3    4    -10    2     a      a     5     2.0
4    5     -5    2     a      a     0     2.0
5   10      5    0     a      a     5     0.0
6    1      0    1     b      a     0     1.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2015-09-30
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 2016-03-04
    • 2018-08-12
    相关资源
    最近更新 更多