【问题标题】:How do I add multiple values from a dictionary to a PySpark Dataframe如何将字典中的多个值添加到 PySpark Dataframe
【发布时间】:2022-01-23 07:48:10
【问题描述】:

我无法创建我需要的整个 PySpark 数据框。我当前的字典是这种格式:

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]|  
+---------+------+-------+----------+---------------------+  

我能够使用此代码为“属性”创建一个 DataFrame:

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 将“关键功能”添加为包含在字典中的列表的列?

【问题讨论】:

    标签: python dataframe dictionary pyspark


    【解决方案1】:

    我认为您的示例输入 d 有点格式错误,因为它将 'Properties'01 置于同一级别,因此顶层有多个 '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|
    +-------+--------+-----------------+-----+-----+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 2023-03-31
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多