【问题标题】:Spark/ Scala- Select Columns Conditionally From DataframeSpark / Scala-从数据框中有条件地选择列
【发布时间】:2017-03-13 07:52:51
【问题描述】:

我有两个配置单元表AB 以及它们各自的数据框df_adf_b

A
+----+----- +-----------+
| id | name | mobile1   |
+----+----- +-----------+
| 1  | Matt | 123456798 |
+----+----- +-----------+
| 2  | John | 123456798 |
+----+----- +-----------+
| 3  | Lena |           |
+----+----- +-----------+

B
+----+----- +-----------+
| id | name | mobile2   |
+----+----- +-----------+
| 3  | Lena | 123456798 |
+----+----- +-----------+

并且想要执行类似的操作

select A.name, nvl(nvl(A.mobile1, B.mobile2), 0) from A left outer join B on A.id = B.id

到目前为止,我想出了

df_a.join(df_b, df_a("id") <=> df_b("id"), "left_outer").select(?)

我不知道如何像在 Hive 查询中那样有条件地选择 mobile1mobile20

有人可以帮我解决这个问题吗?我正在使用 Spark 1.5。

【问题讨论】:

  • 预期输出是什么?
  • @mtoto 这不是我写的确切查询,但我正在尝试检查表 A (df_a) 是否没有 moile no,那么它应该从表 B (df_b )。如果仍未找到,则将 0 设为手机号

标签: scala hadoop apache-spark hive


【解决方案1】:

使用coalesce:

import org.apache.spark.sql.functions._
df_a.join(df_b, df_a("id") <=> df_b("id"), "left_outer").select(
     coalesce(df_a("mobile1"), df_b("mobile2"), lit(0))
)

如果存在则使用mobile1,如果不存在,则使用mobile2,如果不存在则使用0

【讨论】:

  • 我收到此错误not found: value coalesce。我使用的 spark 版本是 1.5.0,scala 是 2.10.4。这会是个问题吗?
  • 谢谢。错误消息消失了。出于某种原因,Ctrl+Shift+O 组合不适用于我的 IDE 中的自动导入。
  • 我也有另一个问题-在select 函数中,我想以特定顺序选择表A 的所有列(实际表有很多列)。我在字符串中有列名和顺序,例如“DFA.name,DFA.id,DFA.address”。我想像df_a.as("DFA").join(df_b, df_a("id") &lt;=&gt; df_b("id"), "left_outer").select( "DFA.name,DFA.id,DFA.address", coalesce(df_a("mobile1"), df_b("mobile2"), lit(0)) )一样全选。这样的事情能做到吗?
  • @Amber 使用 df_a.columns.filter(here filter names): _*
  • 使用* 不能确保我按我需要的顺序获得列:( 我需要的顺序与表中的实际顺序不同,例如,表有顺序@ 987654329@,但我需要name, id, address。我看到我不能在select 函数中使用字符串和列。我可以使用select(df_a("name"), df_a("id"), df_a("address")),但我希望有一种更简单的方法,因为这样我必须提到一百多个列名
【解决方案2】:

您可以使用 spark sql 的 nanvl 函数。 应用后应该类似于:

df_a.join(df_b, df_a("id") <=> df_b("id"), "left_outer")
.select(df_a("name"), nanvl(nanvl(df_a("mobile1"), df_b("mobile2")), 0))

【讨论】:

  • 您提供的链接显示Returns col1 if it is not NaN, or col2 if col1 is NaN NaN 表示不是数字,对吧?如果表格列中没有值,我希望条件起作用
猜你喜欢
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
  • 2019-07-17
  • 2019-11-24
  • 2016-04-26
  • 2020-03-21
相关资源
最近更新 更多