我在以下结构中有一个非常大的表:
user, product, action
user1, productA, actionA
user1, productA, actionB
user1, productA, actionB
user2, productF, actionA
user3, productZ, actionC
我想将其转置为以下内容:
Stage1:检索特定产品X操作
user, productA_actionA, productB_actionA, …, productA_actionB, productB_actionB…
user1, 1, 0, ..., 0,0, ...
user1, 0, 0, ..., 1,0, ...
user1, 0, 0, ..., 1,0, ...
user2, 0, 0, ..., 0,0, ...
我有包含特定组合的数组:
[(productA,actionA) ,(productB,actionA) ,… ,(productA,actionB) ,(productB,actionB) …]
阶段2:对我的用户进行分组,并总结他们的产品和行动
user, productA_actionA, productB_actionA, …, productA_actionB, productB_actionB…
user1, 1, 0, ..., **2**,0, ...
user2, 0, 0, ..., 0,0, ...
我尝试对每个功能使用withColumn
function
,但这需要永远:
for ( (productID,productAction) <- productsCombination ) {
newTable = newTable.withColumn("Product_"+productID+"_"+productAction, when(col("product_action_id") === productAction and col("product_id") === productID, $"product_count").otherwise(0))
以下示例显示了我想要做的事情:
有什么建议吗?
答案 0 :(得分:0)
我无法正确理解问题,但我考虑了您的屏幕截图,这是基于截图的输出。
正如T.Gawęda所说,你应该使用Pivot。请注意,scala> df.show()
+-----+-------+---------------+
| User|Product| Action|
+-----+-------+---------------+
|user1| A| Viewed|
|user1| A| Viewed|
|user1| A| Viewed|
|user1| C| AddToCart|
|user1| A|RemovedFromCart|
|user2| B| Viewed|
|user2| B| Viewed|
|user3| A| Viewed|
|user3| A| AddToCart|
|user4| B| AddToCart|
|user5| A| Viewed|
+-----+-------+---------------+
仅适用于Spark 1.6 +
考虑到这是您的源DataFrame
concat_ws
既然你需要在两列上进行透视,你可以使用Apache Spark提供的groupBy
函数将它们连接成一列,然后透视连接列,在{{1}上执行Users
并在count
上使用Products
作为聚合函数。
df.withColumn("combined", concat_ws("_", $"Product", $"Action"))
.groupBy("User")
.pivot("combined")
.agg(count($"Product")).show()
+-----+-----------+-----------------+--------+-----------+--------+-----------+
| User|A_AddToCart|A_RemovedFromCart|A_Viewed|B_AddToCart|B_Viewed|C_AddToCart|
+-----+-----------+-----------------+--------+-----------+--------+-----------+
|user1| 0| 1| 3| 0| 0| 1|
|user2| 0| 0| 0| 0| 2| 0|
|user3| 1| 0| 1| 0| 0| 0|
|user4| 0| 0| 0| 1| 0| 0|
|user5| 0| 0| 1| 0| 0| 0|
+-----+-----------+-----------------+--------+-----------+--------+-----------+