如何删除数组pyspark结构中的重复元素

2024-09-28 22:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在数据框中有一个列叫做“INFO_CSQ”。我想删除struct中的任何重复元素,这些元素使我无法使用命令df.select("INFO_CSQ.xxx"),因为引用不明确

如果你想要更多的信息,请随时问我。我会尽快回答

编辑我看到许多解决方案都在使用重命名,我看到的所有解决方案都是手动键入strSchema = "array<struct<a_renamed:string,b:bigint,c:bigint>>" 并强制转换到新的数据帧,但是我的模式可以根据输入文件进行更改。

enter image description here

enter image description here


Tags: 数据命令info信息元素编辑df解决方案
1条回答
网友
1楼 · 发布于 2024-09-28 22:24:01

您可以将数据帧转换为RDD,然后再转换回数据帧。重新创建dataframe时,可以提供列名唯一的架构

我使用了一个简化示例,其中fieldnamefield2不是唯一的:

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

相关问题 更多 >