[英]Unable to remove the space from column names in spark scala
我有鑲木地板數據集列名,其中單詞之間有空格,例如: BRANCH NAME
。 現在,當我用"_"
替換空格並嘗試打印該列時,它會導致錯誤。 下面是我的代碼,有多種方法,后面跟着錯誤:
方法一:
Var df= spark.read.parquet("s3://tvsc-lumiq-edl/raw-v2/LMSDB/DESUSR/TBL_DES_SLA_MIS1")
for (c <- df.columns){
df = df.withColumnRenamed(c, c.replace(" ", ""))
}
方法二:
df = df.columns.foldLeft(df)((curr, n) => curr.withColumnRenamed(n, n.replaceAll("\\s", "")))
方法3:
val new_cols = df.columns.map(x => x.replaceAll(" ", ""))
val df2 = df.toDF(new_cols : _*)
錯誤:
org.apache.spark.sql.AnalysisException: Attribute name "BRANCH NAME" contains invalid character(s) among " ,;{}()\n\t=". Please use alias to rename it.;
下面是架構:
scala> df.printSchema()
root
|-- dms_timestamp: string (nullable = true)
|-- BRANCH NAME: string (nullable = true)
|-- BRANCH CODE: string (nullable = true)
|-- DEALER NAME: string (nullable = true)
|-- DEALER CODE: string (nullable = true)
|-- DEALER CATEGORY: string (nullable = true)
|-- PRODUCT: string (nullable = true)
|-- CREATION DATE: string (nullable = true)
|-- CHANNEL TYPE: string (nullable = true)
|-- DELAY DAYS: string (nullable = true)
我也提到了多個 SO 帖子,但沒有幫助。
試試下面的代碼。
df
.select(df.columns.map(c => col(s"`${c}`").as(c.replace(" ",""))):_*)
.show(false)
這對我有用
val dfnew =df.select(df.columns.map(i => col(i).as(i.replaceAll(" ", ""))): _*)
如果所有數據集都在 parquet 文件中,恐怕我們不走運,您必須將它們加載到 Pandas 中,然后進行重命名。
Spark 根本不會讀取列名包含“ ,;{}()\n\t=
” 之間字符的鑲木地板文件。 AFAIK,Spark 開發者拒絕解決這個問題。 它的根本原因在於您的鑲木地板文件本身。 至少根據開發人員的說法,鑲木地板文件首先不應在其列名中包含這些“無效字符”。
請參閱https://issues.apache.org/jira/browse/SPARK-27442 。 它被標記為“不會修復”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.