【问题标题】:How to select list of specific columns (which contain special characters) from pyspark dataframe?如何从 pyspark 数据框中选择特定列(包含特殊字符)的列表?
【发布时间】:2019-11-25 22:55:04
【问题描述】:

我正在尝试从 spark 数据框中选择特定的列。

具体的列列表是:

required_cols = ['123ABC.PM','456DEF.PM']

Spark_df 采用给定格式:

'123ABC.PM', '54SWC.PM', '456DEF.PM', '154AS.LB'
23.5         34.5         400.7        100.3
25.4         37.6         401          100
and so on

我已经试过了:

spark_df_new = spark_df.select(required_cols)

但我收到错误:

"cannot resolve '`123ABC.PM`' given input columns: [123ABC.PM,54SWC.PM, 456DEF.PM,154AS.LB]
``

【问题讨论】:

标签: apache-spark pyspark apache-spark-sql pyspark-sql


【解决方案1】:

使用反引号`字符

required_cols = [`123ABC.PM`,`456DEF.PM`]

【讨论】:

  • 后引号在 Spark SQL SELECT 语句中也适用,如果您的列具有特殊含义,例如函数名
【解决方案2】:

可能作为解决方法,您可以尝试以下方法。

将带有特殊字符的旧列名替换为新列,然后进行选择。

val columns = df.columns

val regex = """[+._,' ]+"""
val replacingColumns = columns.map(regex.r.replaceAllIn(_, "_"))

val resultDF = replacingColumns.zip(columns).foldLeft(df){(tempdf, name) => tempdf.withColumnRenamed(name._2, name._1)}

resultDF.show(false)

df
  .columns
  .foldLeft(df){(newdf, colname) =>
    newdf.withColumnRenamed(colname, colname.replace(" ", "_").replace(".", "_"))
  }

来源: SO

【讨论】:

    【解决方案3】:

    您需要使用 *.
    * 将列表中的元素一一传递给选择。

    spark_df_new = spark_df.select(*required_cols)
    

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 2020-11-15
      相关资源
      最近更新 更多