Python 在数据框上创建产品的每日价格变化
我正在处理具有以下列的数据集: 订单号 订单\项目\标识 产品mrp 单位 销售日期 我想创建一个新的专栏,显示mrp与上次使用该产品相比发生了多大的变化。有没有一种方法可以用熊猫数据框来实现 对不起,如果这个问题很基本,但我对熊猫很陌生 样本数据: 预期数据:Python 在数据框上创建产品的每日价格变化,python,pandas,Python,Pandas,我正在处理具有以下列的数据集: 订单号 订单\项目\标识 产品mrp 单位 销售日期 我想创建一个新的专栏,显示mrp与上次使用该产品相比发生了多大的变化。有没有一种方法可以用熊猫数据框来实现 对不起,如果这个问题很基本,但我对熊猫很陌生 样本数据: 预期数据: 对于每一行数据,我要检查上次销售产品时的价格变化量。您可以按如下方式执行此操作: # define a function that applies rolling window calculationg # taking the di
对于每一行数据,我要检查上次销售产品时的价格变化量。您可以按如下方式执行此操作:
# define a function that applies rolling window calculationg
# taking the difference between the last value and the current
# value
def calc_mrp(ser):
# in case you want the relative change, just
# divide by x[1] or x[0] in the lambda function
return ser.rolling(window=2).apply(lambda x: x[1]-x[0])
# apply this to the grouped 'product_mrp' column
# and store the result in a new column
df['mrp_change']=df.groupby('product_id')['product_mrp'].apply(calc_mrp)
如果在以下数据帧上执行此操作:
Out[398]:
order_id product_id product_mrp units_sold sale_date
0 0 2 647.169280 8 2019-08-23
1 1 0 500.641188 0 2019-08-24
2 2 1 647.789399 15 2019-08-25
3 3 0 381.278167 12 2019-08-26
4 4 2 373.685000 7 2019-08-27
5 5 4 553.472850 2 2019-08-28
6 6 4 634.482718 7 2019-08-29
7 7 3 536.760482 11 2019-08-30
8 8 0 690.242274 6 2019-08-31
9 9 4 500.515521 0 2019-09-01
它产生:
Out[400]:
order_id product_id product_mrp units_sold sale_date mrp_change
0 0 2 647.169280 8 2019-08-23 NaN
1 1 0 500.641188 0 2019-08-24 NaN
2 2 1 647.789399 15 2019-08-25 NaN
3 3 0 381.278167 12 2019-08-26 -119.363022
4 4 2 373.685000 7 2019-08-27 -273.484280
5 5 4 553.472850 2 2019-08-28 NaN
6 6 4 634.482718 7 2019-08-29 81.009868
7 7 3 536.760482 11 2019-08-30 NaN
8 8 0 690.242274 6 2019-08-31 308.964107
9 9 4 500.515521 0 2019-09-01 -133.967197
NaN
s在行中,之前没有相同产品id的订单。也提供一些样本数据和预期输出。你好,terry和Valentino,我已经添加了样本数据并对预期数据进行了解释。