Есть ли способ собрать имена всех полей во вложенной схеме в pyspark - PullRequest
1 голос
/ 05 мая 2020

Я sh, чтобы собрать имена всех полей во вложенной схеме. Данные были импортированы из файла json.

Схема выглядит так:

root
 |-- column_a: string (nullable = true)
 |-- column_b: string (nullable = true)
 |-- column_c: struct (nullable = true)
 |    |-- nested_a: struct (nullable = true)
 |    |    |-- double_nested_a: string (nullable = true)
 |    |    |-- double_nested_b: string (nullable = true)
 |    |    |-- double_nested_c: string (nullable = true)
 |    |-- nested_b: string (nullable = true)
 |-- column_d: string (nullable = true)

Если я использую df.schema.fields или df.schema.names, он просто печатает имена слоя столбца - ни один из вложенных столбцов.

Желаемый результат, который я хочу, - это список python, который содержит все имена столбцов, такие как:

['column_a', 'columb_b', 'column_c.nested_a.double_nested.a', 'column_c.nested_a.double_nested.b', etc...]

Информация существует там, если я хочу написать собственную функцию - но не хватает ли мне доли? Есть ли способ достичь того, что мне нужно?

1 Ответ

1 голос
/ 05 мая 2020

По умолчанию в Spark нет метода, позволяющего сгладить имена схем.

Используйте код из этого сообщения:

def flatten(schema, prefix=None):
    fields = []
    for field in schema.fields:
        name = prefix + '.' + field.name if prefix else field.name
        dtype = field.dataType
        if isinstance(dtype, ArrayType):
            dtype = dtype.elementType

        if isinstance(dtype, StructType):
            fields += flatten(dtype, prefix=name)
        else:
            fields.append(name)

    return fields


df.printSchema()
#root
# |-- column_a: string (nullable = true)
# |-- column_c: struct (nullable = true)
# |    |-- nested_a: struct (nullable = true)
# |    |    |-- double_nested_a: string (nullable = true)
# |    |-- nested_b: string (nullable = true)
# |-- column_d: string (nullable = true)

sch=df.schema

print(flatten(sch))
#['column_a', 'column_c.nested_a.double_nested_a', 'column_c.nested_b', 'column_d']
...