拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何将字典中的多个值添加到PySpark资料帧

如何将字典中的多个值添加到PySpark资料帧

白鹭 - 2022-03-02 1942 0 0

我无法创建我需要的整个 PySpark Dataframe。我目前的字典是这种格式:

d = {0:   
{'Key Features': ['Obese', 'Exercise']},  
'Properties': {'Balding': True, 'Tall': False, 'Obese': True, 'Exercise': False}},  
1:  
{'Key Features': [None]},  
'Properties': {'Balding': True, 'Tall': False, 'Obese': False, 'Exercise': True}},  
...}  

我想以这种格式创建一个资料框:

 --------- ------ ------- ---------- ---------------------   
|'Balding'|'Tall'|'Obese'|'Exercise'|       'Key Features'|  
 --------- ------ ------- ---------- ---------------------   
|     true| false|  false|     false|['Obese', 'Exercise']|  
 --------- ------ ------- ---------- ---------------------   
|     true| false|  false|      true|               [None]|  
 --------- ------ ------- ---------- ---------------------   

我能够使用以下代码为“属性”创建一个资料帧:

df = spark.createDataFrame([d[i]['Properties'] for i in d]).show()  

输出此资料帧:

 --------- ------ ------- ---------- 
|'Balding'|'Tall'|'Obese'|'Exercise'|
 --------- ------ ------- ---------- 
|     true| false|  false|     false|
 --------- ------ ------- ---------- 
|     true| false|  false|      true|
 --------- ------ ------- ---------- 

我曾尝试添加这样的列,但失败了:

df.withColumn('Key Features', array(lit([d[i]['Key Features'] for i in d]) 

但它只是失败并且不会将串列添加为列。我试图创建一个这样的 DataFrame ,但它也不起作用:

df = spark.createDataFrame([d[i]['Key Features'] for i in d]).show()  

输出:输入行没有架构所需的预期值数。提供 1 个值时需要 4 个栏位。
我将如何通过在 createDataFrame 的开头添加或使用 withColumn 将“关键功能”添加为包含在字典中的串列的列?

uj5u.com热心网友回复:

我认为您的示例输入d有点格式错误,因为它'Properties'0and处于同一级别1,因此'Properties'在顶层有多个键。鉴于您如何索引到d,我将假设d看起来像这样。如果我的假设有误,请告诉我,我会尽力纠正答案。

d = {
    0: {
        'Key Features': ['Obese', 'Exercise'],
        'Properties': {'Balding': True, 'Tall': False, 'Obese': True, 'Exercise': False},
    },
    1: {
        'Key Features': [None],
        'Properties': {'Balding': True, 'Tall': False, 'Obese': False, 'Exercise': True},
    },
}

您可以使用它创建所需的资料框。

df = spark.createDataFrame(
    [
        {"Key Features": v["Key Features"], **v["Properties"]}
        for v in d.values()
    ]
)
df.show()
 ------- -------- ----------------- ----- ----- 
|Balding|Exercise|     Key Features|Obese| Tall|
 ------- -------- ----------------- ----- ----- 
|   true|   false|[Obese, Exercise]| true|false|
|   true|    true|           [null]|false|false|
 ------- -------- ----------------- ----- ----- 
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *