使用PySpark:从具有匹配ID的数据框B的值中更新数据框A的列值。

huangapple go评论125阅读模式
英文:

PySpark: Update column values from dataframe A with dataframe B's values with matching ID

问题

假设我们有dfA:

ID Scores
A 20
A 40
A 60
B 10
B 90

和dfB:

ID Scores
A 60
B 90

期望的输出:

ID Scores
A 60
A 60
A 60
B 90
B 90

如何在 PySpark 中根据匹配的 ID 更新 dfA 的分数列与 dfB 的分数列相符?

英文:

Assume we have dfA:

ID Scores
A 20
A 40
A 60
B 10
B 90

and dfB:

ID Scores
A 60
B 90

Expected OUTPUT:

ID Scores
A 60
A 60
A 60
B 90
B 90

How can I update the score column in dfA with dfB's score according to matching ID in PySpark?

答案1

得分: 1

  1. df_1 中将列名 Scores 重命名为 old_scores
  2. 使用内连接来匹配这两个数据框,使用公共键列。
  3. df_1 中删除 old_scores 列。

输出结果如下:

+---+------+
| ID|Scores|
+---+------+
|  A|    60|
|  A|    60|
|  A|    60|
|  B|    90|
|  B|    90|
+---+------+
英文:

Your DataFrames

df_1
+---+------+
| ID|Scores|
+---+------+
|  A|    20|
|  A|    40|
|  A|    60|
|  B|    10|
|  B|    90|
+---+------+

df_2
+---+------+
| ID|Scores|
+---+------+
|  A|    60|
|  B|    90|
+---+------+
  1. Rename the Scores column name to old_scores from df_1 before joining.
df_1 = df_1.withColumnRenamed("Scores", "old_scores")
  1. Use inner join to match the two DataFrames using the common key column.
df = df_1.join(df_2, "ID")
  1. Drop the old_scores column from df_1
df.drop("old_scores").show()

Output:

+---+------+
| ID|Scores|
+---+------+
|  A|    60|
|  A|    60|
|  A|    60|
|  B|    90|
|  B|    90|
+---+------+

huangapple
  • 本文由 发表于 2023年3月10日 01:45:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75688262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定