簡體   English   中英

如何在 Python 中優化 groupby.apply(function)?

[英]How can I optimize the groupby.apply(function) in Python?

我有一個函數,它使用 deque.collections 根據 FIFO 來跟蹤每日庫存。 如果可能,訂單將被履行,並相應地從庫存中扣除。 我在 groupby.apply(my_function) 中使用了一個函數。

我很難在哪里放置第二個循環。 兩個循環單獨運行時都可以正常工作。 但我沒有讓它們結合起來工作。

數據集大約有 150 萬行。 謝謝。

DOS = 7
WIP = 1

df_fin['list_stock'] = 0
df_fin['stock_new'] = 0

def create_stocklist(x):
    x['date_diff'] = x['dates'] - x['dates'].shift()
    x['date_diff'] = x['date_diff'].fillna(0)
    x['date_diff'] = (x['date_diff'] / np.timedelta64(1, 'D')).astype(int)
    x['list_stock'] = x['list_stock'].astype(object)
    x['stock_new'] = x['stock_new'].astype(object)

    var_stock = DOS*[0]
    sl = deque([0],maxlen=DOS)

    for i in x.index:

        order = x['order_bin'][i]

        if x['date_diff'][i] > 0:
            for p in range(0,x['date_diff'][i]):
                if p == WIP:
                    sl.appendleft(x.return_bin[i-1])
                else:
                    sl.appendleft(0)

                sl_list = list(sl)
                sl_list.reverse()

                new_list = []

#from here the loop does not work as I wanted it to work. 
#I want to loop over de created sl_list
#and then start the loop above with the outcome of the loop below.

            for elem in sl_list:
                while order > 0:
                    val = max(0,elem-order)
                    order = (abs(min(0,elem-order)))
                    new_list.append(val)
                    break

                else:
                    new_list.append(elem)

            new_list.reverse()
            x.at[i,'list_stock'] = new_list

            sl = deque(new_list)

    return x

df_fin.groupby(by=['ID']).apply(create_stocklist)

您無權訪問第二個循環中的sl_list ,您應該只在上層范圍內定義它:例如在第一個全局 for 循環之后:

for i in x.index:
        # define it just here
        sl_list = []
        order = x['order_bin'][i]

暫無
暫無

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

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