【问题标题】:Create an array column of key value pairs创建键值对的数组列
【发布时间】:2018-03-20 05:47:57
【问题描述】:

我有一个数据框df 如下:

+---+--------+----+
| Id|    Size| Amt|
+---+--------+----+
| a1|       1|55.0|
| a2|       2|48.0|
| a3|       3|28.0|
+---+--------+----+

这个数据框的架构是:

StructType([
      StructField("Id", StringType(), True),
      StructField("Size", IntegerType(), True),
      StructField("Amt", FloatType(), True)
    ])

当我使用df.write.json("my_output_path") 时,json 文件看起来像:

{"Id":"a1", "Size":1, "Amt":55.0}
{"Id":"a2", "Size":2, "Amt":48.0}
{"Id":"a3", "Size":3, "Amt":28.0}

使用df,我想创建df1,使其具有一个新的数组列(Arr),其中包含现有列的键值对。

df1.write.json("my_new_output_path") 的输出文件应如下所示:

{"Id":"a1", "Size":1, "Amt":55.0, "Arr":[{"Id":"a1","Size":1,"Amt":55.0 }] }
{"Id":"a2", "Size":2, "Amt":48.0, "Arr":[{"Id":"a2","Size":2,"Amt":48.0 }] }
{"Id":"a3", "Size":3, "Amt":28.0, "Arr":[{"Id":"a3","Size":3,"Amt":28.0 }] }

我尝试了以下方法,但它给了我不同的输出:

df1 = df.select('Id', 'Size', 'Amt', array('Id','Size','Amt').alias("Arr"))
df1.write.json("my_new_output_path")

电流输出:

{"Id":"a1", "Size":1, "Amt":55.0, "Arr":["a1", 1 ,55.0] }
{"Id":"a2", "Size":2, "Amt":48.0, "Arr":["a2", 2 ,48.0] }
{"Id":"a3", "Size":3, "Amt":28.0, "Arr":["a3", 3 ,28.0] }

我怎样才能得到预期的输出?任何解决方案或指针将不胜感激。

【问题讨论】:

    标签: python arrays apache-spark pyspark pyspark-sql


    【解决方案1】:

    由于您需要键值对,因此字典会更合适,而不是使用 array 尝试 create_map(在 Scala 中为 map)。此函数采用按键值对分组的列列表(key1、value1、key2、value2、...)。

    df1 = df.select('Id', 'Size', 'Amt', create_map(lit('Id'), 'Id', lit('Size'), 'Size', lit('Amt'), 'Amt').alias("Arr"))
    

    lit 在这里用于创建具有文字字符串值的列。

    然后像之前一样保存新的dataframe,生成的json会如下所示:

    {"Id":"a1","Size":1,"Amt":55.0,"Arr":{"Id":"a1","Size":"1","Amt":"55.0"}}
    {"Id":"a2","Size":2,"Amt":48.0,"Arr":{"Id":"a2","Size":"2","Amt":"48.0"}}
    {"Id":"a3","Size":3,"Amt":28.0,"Arr":{"Id":"a3","Size":"3","Amt":"28.0"}}
    

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 2015-03-22
      • 2017-07-21
      • 1970-01-01
      • 2021-08-25
      相关资源
      最近更新 更多