问题描述
我在数据框中有一列名为“INFO_CSQ”。我想删除结构中任何重复的元素,这些元素使我无法使用命令 df.select("INFO_CSQ.xxx")
,因为引用不明确。
如果您想了解更多信息,请随时问我。我会尽快回复。
编辑
我看到许多解决方案都在使用重命名,我看到的所有解决方案都是手动输入 strSchema = "array<struct<a_renamed:string,b:bigint,c:bigint>>"
并转换为新的数据帧,但是我的架构可以根据输入文件进行更改。
解决方法
您可以将数据帧转换为 RDD,然后再转换回数据帧。重新创建数据框时,您可以提供列名唯一的架构。
我使用了一个简化的示例,其中字段名 field2
不是唯一的:
df = ...
df.printSchema()
#root
# |-- INFO_CSQ: array (nullable = true)
# | |-- element: struct (containsNull = true)
# | | |-- field1: string (nullable = true)
# | | |-- field2: string (nullable = true)
# | | |-- field2: string (nullable = true)
import copy
schema_with_renames = copy.deepcopy(df.schema)
seen_fields = {}
#iterate over all fields and add a suffix where necessary
for f in schema_with_renames[0].dataType.elementType.fields:
name = f.name
suffix = ""
if name in seen_fields:
suffix = seen_fields[name] + 1
seen_fields[name] = suffix
else:
seen_fields[name] = 0
f.name = f.name + str(suffix)
df2 = spark.createDataFrame(df.rdd,schema_with_renames)
df2.printSchema()
#root
# |-- INFO_CSQ: array (nullable = true)
# | |-- element: struct (containsNull = true)
# | | |-- field1: string (nullable = true)
# | | |-- field2: string (nullable = true)
# | | |-- field21: string (nullable = true)
现在您可以删除或忽略重命名的字段 field21
。