Pyspark-计算项目出现在客户转换数据中的百分比
Pyspark- calculate percentage of the item appear in the customer transition data
我的数据集是这样的(这个table是客户的交易table(它记录客户进行的每一笔交易),列表列包含客户在一次交易中购买的产品,我想为每个客户找到他们购买的组合产品 'b' 和 'c' 的百分比是多少
|ID |AMOUNT | List |
|:------|:-----:|-------------:|
| 123| 1 |['a','b','c'] |
| 123| 3 |['a','b','c'] |
| 123| 4 |['b','c'] |
| 123| 4 |['a'] |
| 456| 5 |['a','b','c'] |
| 456| 6 |['b'] |
所以理想的输出 table 我想使用 pyspark 如下所示
|customer |Amount | product 'b' and 'c' percentage |
|123 |[1,3,4,4]| 0.75 |
|456 |[5,6] | 0.5 |
想法是按 ID
分组,然后计算聚合行数两次:
- 所有行和
- 行,其中
List
包含两个元素 b
和 c
使用 array_intersect
from pyspark.sql import functions as F
df.groupBy('ID') \
.agg(
F.count('AMOUNT').alias('cnt'),
F.count(F.when(F.size(F.array_intersect('List', F.array(F.lit('b'),F.lit('c')))) >= 2 ,
F.col('AMOUNT'))).alias('cnt_bc')
)\
.withColumn('result', F.col('cnt_bc') / F.col('cnt')) \
.show()
打印
+---+---+------+------+
| ID|cnt|cnt_bc|result|
+---+---+------+------+
|123| 4| 3| 0.75|
|456| 2| 1| 0.5|
+---+---+------+------+
我的数据集是这样的(这个table是客户的交易table(它记录客户进行的每一笔交易),列表列包含客户在一次交易中购买的产品,我想为每个客户找到他们购买的组合产品 'b' 和 'c' 的百分比是多少
|ID |AMOUNT | List |
|:------|:-----:|-------------:|
| 123| 1 |['a','b','c'] |
| 123| 3 |['a','b','c'] |
| 123| 4 |['b','c'] |
| 123| 4 |['a'] |
| 456| 5 |['a','b','c'] |
| 456| 6 |['b'] |
所以理想的输出 table 我想使用 pyspark 如下所示
|customer |Amount | product 'b' and 'c' percentage |
|123 |[1,3,4,4]| 0.75 |
|456 |[5,6] | 0.5 |
想法是按 ID
分组,然后计算聚合行数两次:
- 所有行和
- 行,其中
List
包含两个元素b
和c
使用 array_intersect
from pyspark.sql import functions as F
df.groupBy('ID') \
.agg(
F.count('AMOUNT').alias('cnt'),
F.count(F.when(F.size(F.array_intersect('List', F.array(F.lit('b'),F.lit('c')))) >= 2 ,
F.col('AMOUNT'))).alias('cnt_bc')
)\
.withColumn('result', F.col('cnt_bc') / F.col('cnt')) \
.show()
打印
+---+---+------+------+
| ID|cnt|cnt_bc|result|
+---+---+------+------+
|123| 4| 3| 0.75|
|456| 2| 1| 0.5|
+---+---+------+------+