pyspark groupby并创建包含其他列的字典的列



我有这个pyspark数据框架

df = spark.createDataFrame([("a", "b", "v1", 1234, 56, 78, 9), ("a", "b", "v2", 987, 6, 543, 21), ("c", "d", "v1", 12, 345, 6, 789), ("c", "d", "v2", 9, 876, 5, 4321)], ("k1", "k2", "k3", "ca", "pa", "cb", "pb"))
df.show()
+---+---+---+----+---+---+----+
| k1| k2| k3|  ca| pa| cb|  pb|
+---+---+---+----+---+---+----+
|  a|  b| v1|1234| 56| 78|   9|
|  a|  b| v2| 987|  6|543|  21|
|  c|  d| v1|  12|345|  6| 789|
|  c|  d| v2|   9|876|  5|4321|
+---+---+---+----+---+---+----+

基本上我想做的是通过对前两个键k1k2分组来转换这个数据框,并使用第三个键k3作为字典的主键,该字典将其他列(ca,pa,cb,pb)的值,并且将包含在一个新列中。这个转换将导致一个数据框架看起来像这样:

+---+---+--------------------------------------------------------------------------------------------------+
|k1 |k2 |k3                                                                                                |
+---+---+--------------------------------------------------------------------------------------------------+
|c  |d  |{"v1": {"pa": 345, "pb": 789, "ca": 12, "cb": 6}, "v2": {"pa": 876, "pb": 4321, "ca": 9, "cb": 5}}|
|a  |b  |{"v1": {"pa": 56, "pb": 9, "ca": 1234, "cb": 78}, "v2": {"pa": 6, "pb": 21, "ca": 987, "cb": 543}}|
+---+---+--------------------------------------------------------------------------------------------------+

为了做到这一点,我写了以下代码,但我认为这段代码可以改进(使用pandas_udf或其他东西),但我没有设法找到一个更好的解决方案,我正在寻找任何建议/指导,可以导致一个更优雅的一个有效的解决方案。

def reoganize_col(list_json):
col_data = {}
for d in list_json:
print(d)
for k,v in d.items(): 
col_data[k] = v
return json.dumps(col_data)
udf_reoganize_col = F.udf(reoganize_col, T.StringType())
df = df.withColumn('x', F.create_map(F.lit('ca'), F.col('ca'),
F.lit('cb'), F.col('cb'),
F.lit('pa'), F.col('pa'),
F.lit('pb'), F.col('pb')))
.groupby(['k1', 'k2']).agg(F.collect_list(F.create_map(F.col('k3'), F.col('x'))).alias('k3'))
df = df.withColumn('k3', udf_reoganize_col(F.col('k3')))

你就快找到解决方案了。我建议您使用to_json而不是UDF来提高性能,并使用struct而不是map来使代码更干净。

(df
.groupBy('k1', 'k2')
.agg(F.collect_list(F.struct('k3', F.struct('pa', 'pb', 'ca', 'cb'))).alias('k3'))
.withColumn('k3', F.to_json(F.map_from_entries('k3')))
.show(10, False)
)
# Output
# +---+---+---------------------------------------------------------------------------------+
# |k1 |k2 |k3                                                                               |
# +---+---+---------------------------------------------------------------------------------+
# |c  |d  |{"v1":{"pa":345,"pb":789,"ca":12,"cb":6},"v2":{"pa":876,"pb":4321,"ca":9,"cb":5}}|
# |a  |b  |{"v1":{"pa":56,"pb":9,"ca":1234,"cb":78},"v2":{"pa":6,"pb":21,"ca":987,"cb":543}}|
# +---+---+---------------------------------------------------------------------------------+

相关内容

  • 没有找到相关文章

最新更新