2016-03-16 31 views
6

Tôi có một bộ dữ liệu gấu trúc rất lớn, và tại một số điểm tôi cần phải sử dụng các chức năng sauLàm thế nào để tăng tốc một con gấu trúc rất chậm áp dụng chức năng?

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']`?? 

và tôi sử dụng áp dụng

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

Rõ ràng, tôi không thể chia sẻ dữ liệu ở đây, nhưng làm bạn thấy một nút cổ chai trong mã của tôi? Có thể là điều arange không? Có rất nhiều kết hợp name-productid trong dữ liệu.

tối thiểu làm việc Ví dụ:

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'] 
+1

Bạn đã thử line-profiling mã? – EnricoGiampieri

+0

Tôi không có ý tưởng làm thế nào để làm điều đó –

+1

có một thư viện cho điều đó, và làm việc tuyệt vời, kiểm tra xem nó ra! Tôi sẽ xem xét, nhưng nó có lẽ phụ thuộc vào dữ liệu. https://github.com/rkern/line_profiler – EnricoGiampieri

Trả lời

0

Không có gì thực sự ưa thích ở đây, chỉ cần tinh chỉnh trong một vài nơi. Có thực sự không cần phải đưa vào một chức năng, vì vậy tôi đã không. Trên dữ liệu mẫu nhỏ này, dữ liệu này nhanh gấp hai lần so với bản gốc.

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) 

Kết quả:

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 
Các vấn đề liên quan