我有一个pyspark数据帧:
Location Month Brand Sector TrueValue PickoutValue
USA 1/1/2021 brand1 cars1 7418 30000
USA 2/1/2021 brand1 cars1 1940 2000
USA 3/1/2021 brand1 cars1 4692 2900
USA 4/1/2021 brand1 cars1
USA 1/1/2021 brand2 cars2 16383104.2 16666667
USA 2/1/2021 brand2 cars2 26812874.2 16666667
USA 3/1/2021 brand2 cars2
USA 1/1/2021 brand3 cars3 75.6% 70.0%
USA 3/1/2021 brand3 cars3 73.1% 70.0%
USA 2/1/2021 brand3 cars3 77.1% 70.0%
每个品牌的月值从2021年1月1日到2021年12月1日。我需要创建另一个列,其中包含基于品牌、行业和订单的TrueValue列的累计总和。 具有%值的行应为累积总和除以月数
我期望的数据帧是:
Location Month Brand Sector TrueValue PickoutValue TotalSumValue
USA 1/1/2021 brand1 cars1 7418 30000 7418
USA 2/1/2021 brand1 cars1 1940 2000 9358
USA 3/1/2021 brand1 cars1 4692 2900 14050
USA 4/1/2021 brand1 cars1 14050
USA 1/1/2021 brand2 cars2 16383104.2 16666667 16383104.2
USA 2/1/2021 brand2 cars2 26812874.2 16666667 43195978.4
USA 3/1/2021 brand2 cars2 43195978.4
USA 1/1/2021 brand3 cars3 75.6% 70.0% 75.6%
USA 3/1/2021 brand3 cars3 73.1% 70.0% 76.3%
USA 2/1/2021 brand3 cars3 77.1% 70.0% 75.3%
对于具有%值的行,这是我需要按月计算累计总和的方式:
(75.6+0)/1=75.6%
(75.6+77.1)/2=76.3%
(75.6+77.1+73.1)/3=75.3%
我可以生成累积和,但无法获得%值的累积和
这是我的代码块:
df=df.withColumn("month_in_timestamp", to_timestamp(df.Month, 'dd/MM/yyyy'))
windowval = (Window.partitionBy('Brand','Sector').orderBy('Month')
.rangeBetween(Window.unboundedPreceding, 0))
df1 = df1.withColumn('TotalSumValue', F.sum('TrueValue').over(windowval))
对于%值的计算似乎是一个累积平均值计算。如果是这样,则可以对不包含
%
的值应用累积和,并对包含%
的值应用累积平均值(计算前先删除百分号)。您可以使用when
-otherwise
应用这两种计算相关问题 更多 >
编程相关推荐