簡體   English   中英

如何加速非常慢的熊貓應用功能?

[英]how to speed-up a very slow pandas apply function?

我有一個非常大的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']

這里沒什么好看的,只是在幾個地方調整過。 實際上沒有必要輸入功能,所以我沒有。 在這個微小的樣本數據上,它的速度大約是原始數據的兩倍。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM