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']
Bạn đã thử line-profiling mã? – EnricoGiampieri
Tôi không có ý tưởng làm thế nào để làm điều đó –
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