Apache Spark基于另一行更新RDD或数据集中的行

时间:2016-10-14 16:09:13

标签: scala apache-spark spark-dataframe rdd apache-spark-dataset

我正在尝试计算如何基于另一行更新某些行。

例如,我有一些数据,如

Id | useraname | ratings | city
--------------------------------
1, philip, 2.0, montreal, ...
2, john, 4.0, montreal, ...
3, charles, 2.0, texas, ...

我想将同一城市的用户更新为同一groupId(1或2)

Id | useraname | ratings | city
--------------------------------
1, philip, 2.0, montreal, ...
1, john, 4.0, montreal, ...
3, charles, 2.0, texas, ...

如何在我的RDD或数据集中实现这一目标?

所以只是为了完整性,如果Id是一个字符串,那么密集的等级将不起作用?

例如?

Id | useraname | ratings | city
--------------------------------
a, philip, 2.0, montreal, ...
b, john, 4.0, montreal, ...
c, charles, 2.0, texas, ...

所以结果如下:

grade | useraname | ratings | city
--------------------------------
a, philip, 2.0, montreal, ...
a, john, 4.0, montreal, ...
c, charles, 2.0, texas, ...

2 个答案:

答案 0 :(得分:2)

执行此操作的一种简洁方法是使用dense_rank()函数中的Window。它会列出Window列中的唯一值。由于cityString列,因此这些列将按字母顺序增加。

import org.apache.spark.sql.functions.rank
import org.apache.spark.sql.expressions.Window

val df = spark.createDataFrame(Seq(
  (1, "philip", 2.0, "montreal"),
  (2, "john", 4.0, "montreal"),
  (3, "charles", 2.0, "texas"))).toDF("Id", "username", "rating", "city")

val w = Window.orderBy($"city")
df.withColumn("id", rank().over(w)).show()

+---+--------+------+--------+
| id|username|rating|    city|
+---+--------+------+--------+
|  1|  philip|   2.0|montreal|
|  1|    john|   4.0|montreal|
|  2| charles|   2.0|   texas|
+---+--------+------+--------+

答案 1 :(得分:0)

尝试:

df.select("city").distinct.withColumn("id", monotonically_increasing_id).join(df.drop("id"), Seq("city"))
相关问题