![](/img/trans.png)
[英]pyspark - Updating a column based on a calculated value from another calculated column
[英]add column dynamically and assign calculated value from another column
我有一些預付銷售訂單,需要根據銷售訂單涵蓋的月數(已付/月)將銷售價值分配給后續月份。 dataframe 看起來像這樣:
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
……
謝謝!
我假設您使用的是 pandas。
首先,您需要獲得銷售月份和年份的所有組合。 這取決於您的邊緣情況和數據。 但為了這個例子:
date_combinations = [(10,2021), (11,2021), (12,2021)]
現在,動態添加列並根據多個其他行填充它們的方法是在整個數據幀上使用“應用”function 並獲得如下行:
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
當然,您需要根據日期跨度和邊緣情況進行調整,特別是如果某些銷售跨越一年。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.