【问题标题】:How to compare two DataFrame (StructType) in python如何在python中比较两个DataFrame(StructType)
【发布时间】:2019-04-09 06:41:01
【问题描述】:

本质上这是比较两个数据帧,我可以将它们的名称与:

def diff(first, second):
    second = set(second)
    return [item for item in first if item not in second]

但我还想不仅在名称上进行比较,还想在数据类型上进行比较

示例数据框如下:

>>> pDF1.schema
StructType(
List(
StructField(Scen_Id,IntegerType,true),
StructField(Flow_Direction,StringType,true),
StructField(Dataset_Type,StringType,true),
StructField(Flag_Extrapolation_Percent_Change_Stay,IntegerType,true)
)
)

>>> pDF2.schema
StructType(
List(
StructField(Scen_Id,StringType,true),
StructField(Flow_Direction,StringType,true),
StructField(Dataset_Type,StringType,true),
StructField(Flag_Extrapolation_Percent_Change_Stay,IntegerType,true)
)
)

您可以从这个特殊的简化示例中看到(通常我们的数据帧包含超过 100 个字段),pDF2 与 pDF1 具有相同的名称/数据类型,但第一个字段具有不同的数据类型。

非常感谢。

【问题讨论】:

    标签: python dataframe schema


    【解决方案1】:

    好的,所以答案确实很简单,如下所示,供以后的读者参考:

    def diff(first, second):
        second = set(second)
        return [item for item in first if item not in second]
    
    dl1_fields = list(pDF1.schema.fields)
    
    dl2_fields = list(pDF2.schema.fields)
    
    print("=========================================================")
    print("schema comparison result:")
    print("=========================================================")
    dl1Notdl2 = diff(dl1_fields, dl2_fields)
    print(str(len(dl1Notdl2)) + " columns in first df but not in second")
    pprint.pprint(dl1Notdl2)
    print("=========================================================")
    dl2Notdl1 = diff(dl2_fields, dl1_fields)
    print(str(len(dl2Notdl1)) + " columns in second df but not in first")
    pprint.pprint(dl2Notdl1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2015-04-30
      • 1970-01-01
      • 2013-05-27
      • 2011-07-19
      • 2019-04-16
      • 2019-03-25
      相关资源
      最近更新 更多