如何从 Spark Data Frame 中删除多列?
How to drop multiple columns from Spark Data Frame?
我有一个 CSV,其中某些列 headers 及其对应的值为空。我想知道如何删除名称为 null
的列?
示例 CSV 如下:
"name"|"age"|"city"|"null"|"null"|"null"
"abcd"|"21" |"7yhj"|"null"|"null"|"null"
"qazx"|"31" |"iuhy"|"null"|"null"|"null"
"foob"|"51" |"barx"|"null"|"null"|"null"
我想删除具有 header 和 null
的所有列,以便输出数据框如下所示:
"name"|"age"|"city"
"abcd"|"21" |"7yhj"
"qazx"|"31" |"iuhy"
"foob"|"51" |"barx"
当我在 spark 中加载此 CSV 时,Spark 将数字附加到空列,如下所示:
"name"|"age"|"city"|"null4"|"null5"|"null6"
"abcd"|"21" |"7yhj"|"null"|"null"|"null"
"qazx"|"31" |"iuhy"|"null"|"null"|"null"
"foob"|"51" |"barx"|"null"|"null"|"null"
Solution found
感谢@MaxU 的回答。我最终的解决方案是:
val filePath = "C:\Users\shekhar\spark-trials\null_column_header_test.csv"
val df = spark.read.format("csv")
.option("inferSchema", "false")
.option("header", "true")
.option("delimiter", "|")
.load(filePath)
val q = df.columns.filterNot(c => c.startsWith("null")).map(a => df(a))
// df.columns.filterNot(c => c.startsWith("null")) this part removes column names which start with null and returns array of string. each element of array represents column name
// .map(a => df(a)) converts elements of array into object of type Column
df.select(q:_*).show
IIUC 你可以这样做:
df = df.drop(df.columns.filter(_.startsWith("null")))
我有一个 CSV,其中某些列 headers 及其对应的值为空。我想知道如何删除名称为 null
的列?
示例 CSV 如下:
"name"|"age"|"city"|"null"|"null"|"null"
"abcd"|"21" |"7yhj"|"null"|"null"|"null"
"qazx"|"31" |"iuhy"|"null"|"null"|"null"
"foob"|"51" |"barx"|"null"|"null"|"null"
我想删除具有 header 和 null
的所有列,以便输出数据框如下所示:
"name"|"age"|"city"
"abcd"|"21" |"7yhj"
"qazx"|"31" |"iuhy"
"foob"|"51" |"barx"
当我在 spark 中加载此 CSV 时,Spark 将数字附加到空列,如下所示:
"name"|"age"|"city"|"null4"|"null5"|"null6"
"abcd"|"21" |"7yhj"|"null"|"null"|"null"
"qazx"|"31" |"iuhy"|"null"|"null"|"null"
"foob"|"51" |"barx"|"null"|"null"|"null"
Solution found
感谢@MaxU 的回答。我最终的解决方案是:
val filePath = "C:\Users\shekhar\spark-trials\null_column_header_test.csv"
val df = spark.read.format("csv")
.option("inferSchema", "false")
.option("header", "true")
.option("delimiter", "|")
.load(filePath)
val q = df.columns.filterNot(c => c.startsWith("null")).map(a => df(a))
// df.columns.filterNot(c => c.startsWith("null")) this part removes column names which start with null and returns array of string. each element of array represents column name
// .map(a => df(a)) converts elements of array into object of type Column
df.select(q:_*).show
IIUC 你可以这样做:
df = df.drop(df.columns.filter(_.startsWith("null")))