【发布时间】:2021-04-26 19:32:11
【问题描述】:
我正在读取一个文件,其中列有值时可以是结构,而没有数据时可以是字符串。内联示例assigned_to 和group 是struct 并且有数据。
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))
当我对数据框进行选择时,这不起作用并出错。
【问题讨论】:
标签: python apache-spark pyspark