我有一些預付的銷售訂單,需要根據銷售訂單涵蓋的月數(已付/月)將銷售價值分配給后續月份。資料框如下所示:
order number of months year start month start year paid
1 2 2021 10 2021 300
2 3 2021 10 2021 300
3 1 2021 11 2021 50
....它應該看起來像
order months year start_month start_year paid 2021_10 2021_11 2021_12
1 2 2021 10 2021 300 150 150
2 3 2021 10 2021 300 100 100 100
3 1 2021 11 2021 50 50
....
謝謝!
uj5u.com熱心網友回復:
我假設您正在使用熊貓。
首先,您需要獲得銷售月份和年份的所有組合。這取決于您的邊緣情況和資料。但為了這個例子:
date_combinations = [(10,2021), (11,2021), (12,2021)]
現在,動態添加列并基于多個其他行填充它們的方法是在整個資料框上使用“應用”函式并獲取如下行:
def fill_date_col(row):
if date[0] < row["start_month"] row["months"] and date[0] >= row["start_month"] and row["start_year"] == date[1] :
return row["paid"]/row["months"]
else:
return None
for date in date_combinations:
df[f"{date[0]}_{date[1]}"] = df.apply(lambda row: fill_date_col(row), axis=1)
這就是結果
order months start_month start_year paid 10_2021 11_2021 12_2021
0 1 2 10 2021 300 150.0 150.0 NaN
1 2 3 10 2021 300 100.0 100.0 100.0
2 3 1 11 2021 50 NaN 50.0 NaN
當然,您需要根據日期跨度和邊緣情況進行調整,尤其是在某些銷售跨度超過一年的情況下。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/387653.html
