【问题标题】:How to remove duplicate element in struct of array pyspark如何删除数组pyspark结构中的重复元素
【发布时间】:2021-05-16 08:12:10
【问题描述】:

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

如果您想了解更多信息,请随时问我。我会尽快回复。

编辑 我看到许多解决方案都在使用重命名,而我看到的所有解决方案都是手动输入 strSchema = "array<struct<a_renamed:string,b:bigint,c:bigint>>" 并转换为新的数据框,但是我的架构是可变的,取决于输入文件。

【问题讨论】:

  • 您如何创建数据框以使“TSL”列重复?
  • 您似乎有两个 TSL 列。如果它们是重复的,则删除一个。如果不是,请重命名。
  • @Vivs 我使用发光库将 VCF 文件作为数据帧读取,原始 VCF 文件包含重复项。 glow.readthedocs.io/en/latest/etl/variant-data.html
  • 根据您的输入,如果列名完全相同,则需要手动指定架构并跳过第一行以避免在读取 VCF 文件时出现标题。
  • @crissal 两者都是重复的。我尝试放弃,但我是 pyspark 的新手。现在我正在寻找处理它的命令。

标签: python pyspark bigdata vcf-vcard glow


【解决方案1】:

您可以将数据帧转换为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2018-02-14
    相关资源
    最近更新 更多