![](/img/trans.png)
[英]How to drop specific column and then select all columns from spark dataframe
[英]How to select specific columns from Spark DataFrame based on the value of another column?
考虑一个包含 4 列c0
、 c1
、 c2
和c3
的 DataFrame df
,其中c0
和c1
是嵌套列(结构类型),另外两个是字符串类型:
root
|-- c0: struct (nullable = true)
| |-- x: string (nullable = true)
| |-- y: string (nullable = true)
|-- c1: struct (nullable = true)
| |-- x: string (nullable = true)
| |-- y: string (nullable = true)
|-- c2: string (nullable = true)
|-- c3: string (nullable = true)
我想根据c3
的值选择c0
或c1
的所有值。
示例:如果c3
值为“d”,我想选择c0.*
else c1.*
这是我迄今为止尝试过但没有运气的方法:
方法:在 select 子句中使用 when 和 else 。
.select(
col("c3"),
col("c4"),
when(col("c3") === "d", col("c0.*").otherwise(col("c1.*"))))
这给出了以下异常:
org.apache.spark.sql.AnalysisException: Invalid usage of '*' in expression 'casewhen';
然后我尝试使用df
而不是使用col
:
.select(
col("c3"),
col("c4"),
when(col("c3") =!= "d", df("c0").otherwise(df("c1"))))
这给出了以下异常:
otherwise() can only be applied on a Column previously generated by when()
对此的任何帮助将不胜感激!
PS:我是 Spark 的初学者 :)
您可以先获取您想要使用的结构,然后使用*
来选择这样的嵌套字段:
df.withColumn("c01", when($"c3" === "d", $"c0").otherwise($"c1"))
.select($"c2", $"c3", $"c01.*")
对于另一个错误:
else() 只能应用于先前由 when() 生成的 Column
当您在df("c0")
而不是when
列上调用时,您只是缺少一个括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.