首页 文章

如何使用从镶木地板文件中读取的火花数据框的空格来删除/替换列名?

提问于
浏览
2

我正在处理的数据集在其列中有空格,我在尝试重命名spark数据帧列名时遇到了问题 . 尝试了stackoverflow中几乎所有可用的解决方案 . 似乎没什么用 .

Note: The file must be a parquet file .

df.printSchema


|-- Type: string (nullable = true)
|-- timestamp: string (nullable = true)
|-- ID: string (nullable = true)
|-- Catg Name: string (nullable = true)
|-- Error Msg: string (nullable = true)

df.show()
Error:

警告:有一个弃用警告;使用-deprecation重新运行以获取详细信息org.apache.spark.sql.AnalysisException:属性名称“Catg Name”包含“,; {}()\ n \ t =”中的无效字符 . 请使用别名重命名 .

Tried:

df.select(df.col("Catg Name").alias("Catg_Name"))

然后 df.printSchema


|-- Type: string (nullable = true)
|-- timestamp: string (nullable = true)
|-- ID: string (nullable = true)
|-- Catg_Name: string (nullable = true)
|-- Error_Msg: string (nullable = true)

效果很好但是当我使用 df.show() 时它会抛出相同的错误 .

警告:有一个弃用警告;使用-deprecation重新运行以获取详细信息org.apache.spark.sql.AnalysisException:属性名称“Catg Name”包含“,; {}()\ n \ t =”中的无效字符 . 请使用别名重命名 .

1 回答

  • 2

    通过删除列名称中的空格并重新分配给Dataframe,这个想法怎么样?

    val df1 = df.toDF("col 1","col 2","col 3") // Dataframe with spaces in column names
    
    val new_cols =  df1.columns.map(x => x.replaceAll(" ", "")) // new column names array with spaces removed
    
    val df2 = df1.toDF(new_cols : _*) // df2 with new column names(spaces removed)
    

相关问题