繁体   English   中英

Spark Scala DF。 在处理同一列的某些行时将新列添加到DF

[英]Spark Scala DF. add a new Column to DF based in processing of some rows of the same column

亲爱的,我是SparK Scala的新手,并且我有两列DF:“ UG”和“ Counts”,我希望获得此列表中公开的Third How。

DF:UG,计数,CUG(各列)

  • 共12 4
  • 共23 4
  • 134 3
  • 爱68 2
  • 痛苦3 1
  • 18 3
  • 爱100 2
  • 共23 4
  • 12 3
  • 共11 4

我需要添加一个称为“ CUG”的新列,其中第三个暴露出来,其中CUG(i)是UG中的string(i)出现在整个列中的次数。

我尝试了以下方案:

像df中的上一张表一样具有DF。 我做了一个sql UDF函数来计算字符串在“ UG”列中出现的次数,即:

val NW1 = (w1:String) => { 
  df.filter($"UG".like(w1.substring(1,(w1.length-1))).count() 
}:Long
val sqlfunc = udf(NW1)
val df2= df.withColumn("CUG",sqlfunc(col("UG")))

但是当我尝试时,... 没有用 我得到了Null Point异常错误。 UDF方案孤立地工作,但在DF中不起作用。 我该怎么办才能使用DF获得要求的结果。

提前致谢。 jm3

因此,您可以做的是首先计算按UG列分组的行数,该列将提供您需要的第三列,然后与原始数据帧合并。 如果需要,可以使用withColumnRenamed函数来重命名列名称。

scala> import org.apache.spark.sql.functions._

scala> myDf.show()
+----+------+
|  UG|Counts|
+----+------+
|  of|    12|
|  of|    23|
| the|   134|
|love|    68|
|pain|     3|
| the|    18|
|love|   100|
|  of|    23|
| the|    12|
|  of|    11|
+----+------+     


scala> myDf.join(myDf.groupBy("UG").count().withColumnRenamed("count", "CUG"), "UG").show()
+----+------+---+
|  UG|Counts|CUG|
+----+------+---+
|  of|    12|  4|
|  of|    23|  4|
| the|   134|  3|
|love|    68|  2|
|pain|     3|  1|
| the|    18|  3|
|love|   100|  2|
|  of|    23|  4|
| the|    12|  3|
|  of|    11|  4|
+----+------+---+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM