pyspark:如何在Dataframe的arraytype列中获取structtype中的所有元素名?

6uxekuva  于 2021-07-14  发布在  Spark
关注(0)|答案(2)|浏览(459)

我有一个类似这样的Dataframe:

|-- name: string (nullable = true)
 |-- age: string (nullable = true)
 |-- job: string (nullable = true)
 |-- hobbies: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- favorite: string (nullable = true)
 |    |    |-- non-favorite: string (nullable = true)

我想得到这些信息:

['favorite', 'non-favorite']

但是,我找到的唯一最接近的解决方案是将explode函数用于 withColumn ,但这是基于我已经知道元素名称的假设。但是我想做的是,在不知道元素名的情况下,我只想用列名得到元素名,在这里是“爱好”。有没有一个好的方法来获取任何给定列中的所有元素名?

yc0p9oo0

yc0p9oo01#

对于具有此架构的给定Dataframe:

df.printSchema()

root
 |-- hobbies: array (nullable = false)
 |    |-- element: struct (containsNull = false)
 |    |    |-- favorite: string (nullable = false)
 |    |    |-- non-favorite: string (nullable = false)

可以选择结构的字段名:

struct_fields = df.schema['hobbies'].dataType.elementType.fieldNames()

# output: ['favorite', 'non-favorite']
ibps3vxo

ibps3vxo2#

pyspark.sql.types.StructType.fieldnames 你应该得到你想要的。

fieldNames()

Returns all field names in a list.

>>> struct = StructType([StructField("f1", StringType(), True)])
>>> struct.fieldNames()
['f1']

你的情况是

dataframe.hobbies.getItem(0).fieldnames()

相关问题