pyspark将列合并到键、值对列表中(没有udf)

d7v8vwbk  于 2021-07-13  发布在  Spark
关注(0)|答案(2)|浏览(358)

我想创建一个新列,它是其他一些列的json表示。列表中的键、值对。
资料来源:
Ottawa5控制面板上的原始目的地计数10
我想要的是:
origindestinationcountjsontorontoottawa5[{“origin”:“toronto”},{“destination”,“ottawa”},{“count”:“5”}]montrealvancouver10[{“origin”:“montreal”},{“destination”,“vancouver”},{“count”:“10”}]
(一切都可以是一个字符串,无所谓)。
我试过这样的方法:

df.withColumn('json', to_json(struct(col('origin'), col('destination'), col('count'))))

但它会创建一个包含所有 key:value 在一个对象中成对:

{"origin":"United States","destination":"Romania"}

如果没有自定义项,这可能吗?谢谢!

2admgd59

2admgd591#

解决这个问题的方法:

import pyspark.sql.functions as F

df2 = df.withColumn(
    'json', 
    F.array(
        F.to_json(F.struct('origin')),
        F.to_json(F.struct('destination')),
        F.to_json(F.struct('count'))
    ).cast('string')
)

df2.show(truncate=False)
+--------+-----------+-----+--------------------------------------------------------------------+
|origin  |destination|count|json                                                                |
+--------+-----------+-----+--------------------------------------------------------------------+
|toronto |ottawa     |5    |[{"origin":"toronto"}, {"destination":"ottawa"}, {"count":"5"}]     |
|montreal|vancouver  |10   |[{"origin":"montreal"}, {"destination":"vancouver"}, {"count":"10"}]|
+--------+-----------+-----+--------------------------------------------------------------------+
nafvub8i

nafvub8i2#

另一种方法是在调用 to_json :

from pyspark.sql import functions as F

df1 = df.withColumn(
    'json',
    F.to_json(F.array(*[F.create_map(F.lit(c), F.col(c)) for c in df.columns]))
)

df1.show(truncate=False)

# +--------+-----------+-----+------------------------------------------------------------------+

# |origin  |destination|count|json                                                              |

# +--------+-----------+-----+------------------------------------------------------------------+

# |toronto |ottawa     |5    |[{"origin":"toronto"},{"destination":"ottawa"},{"count":"5"}]     |

# |montreal|vancouver  |10   |[{"origin":"montreal"},{"destination":"vancouver"},{"count":"10"}]|

# +--------+-----------+-----+------------------------------------------------------------------+

相关问题