我们有一个DataFrame
看起来像这样:
DataFrame[event: string, properties: map<string,string>]
请注意,有两列:event
and properties
。我们如何拆分或压平properties
根据中的键值将列分成多列map
?
我注意到我可以做这样的事情:
newDf = df.withColumn("foo", col("properties")["foo"])
从而产生一个Dataframe
of
DataFrame[event: string, properties: map<string,string>, foo: String]
但随后我就必须对所有键一一进行这些操作。有没有办法自动完成所有这些?例如,如果有foo
, bar
, baz
作为中的键properties
,我们可以压平map
:
DataFrame[event: string, foo: String, bar: String, baz: String]
您可以使用explode()
功能 - 它通过创建两个附加列来展平地图 -key
and value
对于每个条目:
>>> df.printSchema()
root
|-- event: string (nullable = true)
|-- properties: map (nullable = true)
| |-- key: string
| |-- value: string (valueContainsNull = true)
>>> df.select('event', explode('properties')).printSchema()
root
|-- event: string (nullable = true)
|-- key: string (nullable = false)
|-- value: string (nullable = true)
如果您有一列具有可以分组依据的唯一值,则可以使用数据透视表。例如:
df.withColumn('id', monotonically_increasing_id()) \
.select('id', 'event', explode('properties')) \
.groupBy('id', 'event').pivot('key').agg(first('value'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)