使用以下两个数据帧架构的示例:
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