我有一个看起来像这样的数据名望

Sno|UserID|TypeExp
1|JAS123|MOVIE
2|ASP123|GAMES
3|JAS123|CLOTHING
4|DPS123|MOVIE
5|DPS123|CLOTHING
6|ASP123|MEDICAL
7|JAS123|OTH
8|POQ133|MEDICAL
.......
10000|DPS123|OTH

UserID 是标识用户的列,TypeExp 列定义了该月的支出类型,现在我可能有 5 种不同的支出,即



现在我想将它转换为用户级数据帧,其中有一个 0 或 1 二进制变量存储信息天气与否用户“X”已完成上述支出类型

例如在上面的快照数据帧输出应该看起来像
User| TypeExpList         #Type list is this array corresponding entry's [MOVIE,GAMES,CLOTHING,MEDICAL,OTH]
JAS123 |[1,0,1,0,1]      #since user has done expenditure on Movie,CLOTHING,OTHER Category
ASP123 |[0,1,0,1,0]       #since User expenditure on  GAMES & MEDICAL
DPS123 |[1,0,1,0,1]         #since user expenditure on  MOVIE,CLOTHING & OTHER
POQ133 |[0,0,0,1,0]        #since User Expenditure on MEDICAL only

最佳答案

这是你的输入数据集。

$ cat input.csv
Sno|UserID|TypeExp
1|JAS123|MOVIE
2|ASP123|GAMES
3|JAS123|CLOTHING
4|DPS123|MOVIE
5|DPS123|CLOTHING
6|ASP123|MEDICAL
7|JAS123|OTH
8|POQ133|MEDICAL

这样,您就可以在 pivot 上对 groupBy 执行 UserID
val bins = spark
  .read
  .option("sep", "|")
  .option("header", true)
  .csv("input.csv")
  .groupBy("UserID")
  .pivot("TypeExp")
  .count
  .na
  .fill(0)
scala> bins.show
+------+--------+-----+-------+-----+---+
|UserID|CLOTHING|GAMES|MEDICAL|MOVIE|OTH|
+------+--------+-----+-------+-----+---+
|POQ133|       0|    0|      1|    0|  0|
|JAS123|       1|    0|      0|    1|  1|
|DPS123|       1|    0|      0|    1|  0|
|ASP123|       0|    1|      1|    0|  0|
+------+--------+-----+-------+-----+---+

你有你的 0 s 和 1 s。最后一个技巧是在列上使用 array 来构建适当的输出,其中位置表示支出。
val solution = bins.select(
  $"UserID" as "User",
  array("MOVIE","GAMES","CLOTHING","MEDICAL","OTH") as "TypeExpList")
scala> solution.show
+------+---------------+
|  User|    TypeExpList|
+------+---------------+
|POQ133|[0, 0, 0, 1, 0]|
|JAS123|[1, 0, 1, 0, 1]|
|DPS123|[1, 0, 1, 0, 0]|
|ASP123|[0, 1, 0, 1, 0]|
+------+---------------+

鉴于支出可能发生零次、一次或多次,超过支出的 count 可能会给出 01 或更高的数字。

您可以使用 UDF 对值进行二值化,并确保仅使用 0 s 和 1 s。
val binarizer = udf { count: Long => if (count > 0) 1 else 0 }
val binaryCols = bins
  .columns
  .filterNot(_ == "UserID")
  .map(col)
  .map(c => binarizer(c) as c.toString)
val selectCols = ($"UserID" as "User") +: binaryCols
val solution = bins
  .select(selectCols: _*)
  .select(
    $"User",
    array("MOVIE","GAMES","CLOTHING","MEDICAL","OTH") as "TypeExpList")
scala> solution.show
+------+---------------+
|  User|    TypeExpList|
+------+---------------+
|POQ133|[0, 0, 0, 1, 0]|
|JAS123|[1, 0, 1, 0, 1]|
|DPS123|[1, 0, 1, 0, 0]|
|ASP123|[0, 1, 0, 1, 0]|
+------+---------------+

关于apache-spark - 如何转置数据帧以计算值是否存在的标志?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47568665/

10-10 14:05
查看更多