[英]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.