【问题标题】:How to encode the grouped data in spark.dataframe?如何对 spark.dataframe 中的分组数据进行编码?
【发布时间】:2019-08-07 09:05:10
【问题描述】:

我在 spark.dataframe A 中有类似的数据:

Ben       1
Ben       2
Ben       4
Ben       3
Jerry     2
Jerry     2
Jane      3
Jane      5
James     1
James     1

我们的 Action_id 范围是 1-5。 我们想像这样得到 spark.dataframe B:

Name     Action_id=1    Action_id=2   Action_id=3  Action_id=4  Action_id=5
Ben          1              1            1               1            0
Jane         0              0            1               0            1
Jerry        0              2            0               0            0            
James        2              0            0               0            0

例如,(Ben,Action_id=1) 中的 '1' 表示在前一个数据帧中,Ben 执行了一次动作 1。

如何将数据帧 A 转换为数据帧 B?

【问题讨论】:

标签: pyspark apache-spark-sql


【解决方案1】:

您正在寻找使用 Count 聚合的 PivotTable

在 Scala 中:

import org.apache.spark.sql.{functions => F}

val df = Seq(("Ben", 1),
("Ben", 2),
("Ben", 4),
("Ben", 3),
("Jerry", 2),
("Jerry", 2),
("Jane", 3),
("Jane", 5),
("James", 1),
("James", 1)).toDF("Name", "Action_id")

df.groupBy("Name").pivot("Action_id").agg(F.count("Action_id")).na.fill(0).show

我现在无法访问 pyspark shell,但这应该是这样的:

import pyspark.sql.functions as F

(df
    .groupby(df.Name)
    .pivot("Action_id")
    .agg(F.count("Action_id"))
    .na.fill(0)
    .show())

【讨论】:

    猜你喜欢
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2020-02-18
    • 2010-10-09
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多