【问题标题】:compare schema ignoring nullable比较架构忽略可为空的
【发布时间】:2018-05-30 16:29:49
【问题描述】:

我正在尝试比较 2 个数据框的架构。 基本上,列和类型是相同的,但“可为空”可以不同:

数据框 A

StructType(List(
StructField(ClientId,StringType,True),
StructField(PublicId,StringType,True),
StructField(ExternalIds,ArrayType(StructType(List(
    StructField(AppId,StringType,True),
    StructField(ExtId,StringType,True),
)),True),True),
....

数据框 B

StructType(List(
StructField(ClientId,StringType,True),
StructField(PublicId,StringType,False),
StructField(ExternalIds,ArrayType(StructType(List(
    StructField(AppId,StringType,True),
    StructField(ExtId,StringType,False),
)),True),True),
....

当我执行df_A.schema == df_B.schema 时,显然是False。 但是我想忽略“nullable”参数,不管是false还是true,如果结构相同,应该返回True

有可能吗?

【问题讨论】:

  • 把所有的假换成真然后比较
  • A 和 B 由 2 个不同的进程生成。我无法改变它们。我只是想比较一下

标签: apache-spark pyspark


【解决方案1】:

使用以下两个 DataFrame 模式的示例:

df_A.printSchema()
#root
# |-- ClientId: string (nullable = true)
# |-- PublicId: string (nullable = true)
# |-- PartyType: string (nullable = true)

df_B.printSchema()
#root
# |-- ClientId: string (nullable = true)
# |-- PublicId: string (nullable = true)
# |-- PartyType: string (nullable = false)

假设字段顺序相同,您可以访问架构中每个字段的namedataType 并将它们压缩以进行比较:

print(
    all(
        (a.name, a.dataType) == (b.name, b.dataType) 
        for a,b in zip(df_A.schema, df_B.schema)
    )
)
#True

如果顺序不同,可以比较排序后的字段:

print(
    all(
        (a.name, a.dataType) == (b.name, b.dataType) 
        for a,b in zip(
            sorted(df_A.schema, key=lambda x: (x.name, x.dataType)), 
            sorted(df_B.schema, key=lambda x: (x.name, x.dataType))
        )
    )
)
#True

如果两个 DataFrame 的列数可能不同,您可以先比较架构长度作为短路检查 - 如果失败,请不要费心遍历字段:

print(len(df_A.schema) == len(df_B.schema))
#True

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 2014-02-21
    • 2017-11-30
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多