在Spark中有数据帧df
:
|-- array_field: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- a: string (nullable = true)
| | |-- b: long (nullable = true)
| | |-- c: long (nullable = true)
如何将字段array_field.a
重命名为array_field.a_renamed
?
[更新]:
.withColumnRenamed()
不适用于嵌套字段,因此我尝试了这种老套且不安全的方法:
# First alter the schema:
schema = df.schema
schema['array_field'].dataType.elementType['a'].name = 'a_renamed'
ind = schema['array_field'].dataType.elementType.names.index('a')
schema['array_field'].dataType.elementType.names[ind] = 'a_renamed'
# Then set dataframe's schema with altered schema
df._schema = schema
我知道设置私有属性不是一个好的实践,但是我不知道其他方法来设置df的模式
我想我是在正确的轨道上,但是df.printSchema()
仍然显示了array_field.a
的旧名称,尽管df.schema == schema
是True
可以在数据帧的架构上递归,以创建具有所需更改的新架构。
PySpark中的模式是一种结构类型,它包含一个结构字段列表,每个结构字段可以包含一些primitve类型或另一个结构类型。
这意味着我们可以根据类型是否为结构类型来决定是否要递归。
下面是一个带注释的示例实现,它向您展示了如何实现上述想法。
Python
无法修改单个嵌套字段。你必须重建一个完整的结构。在这种情况下,最简单的解决方案是使用
cast
。首先是一些进口产品:
以及示例数据:
让我们确认模式与您的案例相同:
可以将新架构定义为字符串:
或
DataType
:斯卡拉
在Scala中也可以使用相同的技术:
或者
可能的改进:
如果使用表示性数据操作或JSON处理库,则可以更容易地将数据类型转储到} ):
dict
或JSON字符串,并从中获取数据类型,例如(Python/^{相关问题 更多 >
编程相关推荐