【发布时间】:2018-03-28 08:44:34
【问题描述】:
我有一个 CSV,其中一些列标题及其对应的值为空。我想知道如何删除名称为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"
我想删除所有标题为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"
找到解决方案
感谢@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
【问题讨论】:
标签: csv apache-spark spark-dataframe