首页 > 解决方案 > 使用 Pyspark 动态重命名数据框列

问题描述

我正在读取一个文件,其中列有值时可以是结构,否则在没有数据时可以是字符串。内联示例 assign_to 和 group 是结构并具有数据。

root
 |-- number: string (nullable = true)
 |-- assigned_to: struct (nullable = true)
 |    |-- display_value: string (nullable = true)
 |    |-- link: string (nullable = true)
 |-- group: struct (nullable = true)
 |    |-- display_value: string (nullable = true)
 |    |-- link: string (nullable = true)

为了展平 JSON,我正在执行以下操作,

df23 = spark.read.parquet("dbfs:***/test1.parquet")
val_cols4 = []

#the idea is the day when the data type of the columns in struct I dynamically extract values otherwise create new columns and default to None.
for name, cols in df23.dtypes:
  if 'struct' in cols:
    val_cols4.append(name+".display_value") 
  else:
    df23 = df23.withColumn(name+"_value", lit(None))

现在,如果我必须使用 val_cols4 从数据框 df23 中进行选择,所有结构列都具有相同的名称“display_value”。

root
 |-- display_value: string (nullable = true)
 |-- display_value: string (nullable = true)

如何将列重命名为适当的值?我尝试了以下,

for name, cols in df23.dtypes:
  if 'struct' in cols:
    val_cols4.append("col('"+name+".display_value').alias('"+name+"_value')") 
  else:
    df23 = df23.withColumn(name+"_value", lit(None))

当我在数据框上进行选择时,这不起作用并且出错。

标签: pythonapache-sparkpyspark

解决方案


您可以将别名列对象而不是字符串附加到val_cols4,例如

from pyspark.sql.functions import col, lit

val_cols4 = []

for name, cols in df23.dtypes:
  if 'struct' in cols:
    val_cols4.append(col(name+".display_value").alias(name+"_value")) 
  else:
    df23 = df23.withColumn(name+"_value", lit(None))

然后您可以选择列,例如

newdf = df23.select(val_cols4)

推荐阅读