我正在分析市场上的销售情况,无法决定如何使用成本价,这取决于我更改成本价的日期。
比如说
我在3月12日收到了一份订单,商品A,成本价是100美元。
之后我在3月20日将成本价从10美元更改为110美元。
接下来,我在 3 月 25 日收到了订单,商品 A。
然后我构建了一份报告,其中包括 3 月份的所有销售额。
3 月 12 日起的订单 A 项的成本价为 100 美元。 3 月 25 日起的订单 A 项的成本价为 110 美元。
如果我不更改成本价 - Price_change_date 列为空,则报告中的成本价不会更改,并且我使用 cost_price 列中的值。
如果有必要,我可以重建表cost_price。
我的桌子看起来像这样:
订单表:
orders_test = {
'order_id': ['82514913-0085-1', '82514913-0085-1', '82514913-0090-1', '82514913-0090-1'],
'article_id': ['99823WH2MO11093_34', '99823WH2MO11093_34', '99823WH2MO11093_34', '99823WH2MO11093_34'],
'profit': [1042.91, 1042.91, 2000, 2000],
'order_date': ['01-15-2024', '01-21-2024', '02-15-2024', '02-20-2024']
}
orders_test = pd.DataFrame(orders_test)
orders_test['order_date'] = pd.to_datetime(orders_test['order_date'])
成本价表:
cost_price_test = {
'article_id': ['99823WH2MO11093_34', '99823WH2MO11093_34', '99823WH2MO11093_34'],
'cost_price': [100, 110, 120],
'price_change_date': ['01-10-2024', '01-20-2024', '02-10-2024'],
'new_cost_price': [110, 120, 100]
}
cost_price_test = pd.DataFrame(data)
cost_price_test['price_change_date'] = pd.to_datetime(cost_price_test['price_change_date'])
想要的结果如下:
order_id article_id profit order_date cost_price
0 82514913-0085-1 99823WH2MO11093_34 1042.91 01-15-2024 100
1 82514913-0085-2 99823WH2MO11093_34 1042.91 01-21-2024 120
2 82514913-0090-3 99823WH2MO11093_34 2000.00 02-15-2024 120
3 82514913-0090-4 99823WH2MO11093_34 2000.00 02-20-2024 110
有人可以帮我吗?谢谢!
最初假设这些数据帧:
orders_test:
order_id article_id profit order_date
0 82514913-0085-1 99823WH2MO11093_34 1042.91 2024-01-15
1 82514913-0085-2 99823WH2MO11093_34 1042.91 2024-01-21
2 82514913-0090-3 99823WH2MO11093_34 2000.00 2024-02-15
3 82514913-0090-4 99823WH2MO11093_34 2000.00 2024-02-20
cost_price_test:
article_id cost_price price_change_date new_cost_price
0 99823WH2MO11093_34 100 2024-01-10 110
1 99823WH2MO11093_34 110 2024-01-20 120
2 99823WH2MO11093_34 120 2024-02-10 100
how='left'
;order_date
;order_date
早于 price_date_change
的行;order_id
和 article_id
删除重复行,保留最后一行。orders_test = pd.merge(orders_test, cost_price_test, how="left").sort_values(
"order_date"
)
orders_test = orders_test.loc[
orders_test["order_date"] >= orders_test["price_change_date"]
].drop_duplicates(["order_id", "article_id"], keep="last")
order_id article_id profit order_date cost_price price_change_date new_cost_price
0 82514913-0085-1 99823WH2MO11093_34 1042.91 2024-01-15 100 2024-01-10 110
4 82514913-0085-2 99823WH2MO11093_34 1042.91 2024-01-21 110 2024-01-20 120
8 82514913-0090-3 99823WH2MO11093_34 2000.00 2024-02-15 120 2024-02-10 100
11 82514913-0090-4 99823WH2MO11093_34 2000.00 2024-02-20 120 2024-02-10 100