apache-spark - 如何从 Pyspark 数据框中的列表值创建列
问题描述
我有一个 pyspark 数据框,如下所示:
Subscription_id Subscription parameters
5516 ["'catchupNotificationsEnabled': True","'newsNotificationsEnabled': True","'autoDownloadsEnabled': False"]
我需要输出数据框为:
Subscription_id catchupNotificationsEnabled newsNotificationsEnabled autoDownloadsEnabled
5516 True True False
我如何在 Pyspark 中实现这一点?我尝试了几个使用 UDF 的选项,但都没有成功。
任何帮助是极大的赞赏。
解决方案
你可以使用类似下面的东西
>>> df.show()
+---------------+-----------------------+
|Subscription_id|Subscription_parameters|
+---------------+-----------------------+
| 5516| ["'catchupNotific...|
+---------------+-----------------------+
>>>
>>> df1 = df.select('Subscription_id')
>>>
>>> data = df.select('Subscription_parameters').rdd.map(list).collect()
>>> data = [i[0][1:-1].split(',') for i in data]
>>> data = {i.split(':')[0][2:-1]:i.split(':')[1].strip()[:-1] for i in data[0]}
>>>
>>> df2 = spark.createDataFrame(sc.parallelize([data]))
>>>
>>> df3 = df1.crossJoin(df2)
>>>
>>> df3.show()
+---------------+--------------------+---------------------------+------------------------+
|Subscription_id|autoDownloadsEnabled|catchupNotificationsEnabled|newsNotificationsEnabled|
+---------------+--------------------+---------------------------+------------------------+
| 5516| False| True| True|
+---------------+--------------------+---------------------------+------------------------+
推荐阅读
- javascript - hichart缩放时hichart的图形会丢失左侧或右侧的列
- c# - 将范围作为参数从 excel 传递到 c# excel-dna
- laravel - Laravel 总是设置默认值
- php - f在href中写引号
- entity-framework - EF Core 2.1.2 和 .net core 2.0 - Linq2Entities 导致“必须是可简化节点”错误
- android - 检测音频文件(如(.mp3,.WAV)中声音的最大振幅
- javascript - 点击时不应该对孩子起作用
- c# - C#/XAML/WPF 简单节点编辑器
- sql - 如何在postgresql中将字符串中的所有内容获取到第二个或第三个逗号?
- sql - 在具有多个百分比行的“选择不同”查询中计算占总数的新百分比