代码之家  ›  专栏  ›  技术社区  ›  Steven

比较架构忽略可为空

  •  3
  • Steven  · 技术社区  · 8 年前

    我试图比较两个数据帧的模式。 基本上,列和类型是相同的,但是“可空”可以是不同的:

    数据帧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 .

    有可能吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   pault Tanjin    8 年前

    使用以下两个数据帧架构的示例:

    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)
    

    假设字段的顺序相同,则可以访问 name dataType 架构中的每个字段,并将其压缩以进行比较:

    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
    

    如果两个数据帧可能具有不同的列数,则可以首先比较架构长度,作为短路检查-如果失败,则不必重复字段:

    print(len(df_A.schema) == len(df_B.schema))
    #True
    
    推荐文章