我有一个Python字典列表,我想将其添加为pyspark数据帧中的新列,例如列表中的所有任何单个项目都将转换为新列中的单元格。 例如,当我尝试将其转换为 pandas 时,添加列并将其转换为 py Spark 数据会损坏,我可以找出正确的函数组合来添加数据而不使用 pandas 我尝试使用 lit 但或将 structType 添加到 no成功 感谢您的帮助。
这是数据示例
my_list = [{"example1": {"subkey_example1": {"ex1": "2", "ex2": "4"},
"example2": {"subkey_example2": {"ex3": "1", "ex4": "3"}}},
{"example3": {"subkey_example3": {"ex5": "4", "ex6": "2"},
"example4": {"subkey_example4": {"ex7": "1", "ex8": "3"}}}
这是表格的示例
+-------+-------+
|column1|column2|
+-------+-------+
| data1 | data1 |
| data2 | data2 |
+-------+-------+
期望的值是:
+-------+-------+--------------------------------+
|column1|column2| column3 |
+-------+-------+--------------------------------+
| data1 | data1 | {"example1": |
| | | {"subkey_example1": |
| | | {"ex1": "2", "ex2": "4"}, |
| | | "example2": |
| | | {"subkey_example2": |
| | | {"ex3": "1", "ex4": "3"}}} |
+-------+-------+--------------------------------+
| data2 | data2 | {"example3": |
| | | {"subkey_example3": |
| | | {"ex5": "4", "ex6": "2"}, |
| | | "example4": |
| | | {"subkey_example4": |
| | | {"ex7": "1", "ex8": "3"}}} |
+-------+-------+--------------------------------+
要将字典列表添加为 PySpark DataFrame 中的新列,您可以使用 pyspark.sql.functions.struct() 函数创建具有所需结构的新列。
从 pyspark.sql.functions 导入结构,col
df = Spark.createDataFrame([ (1, 1), (2, 2) ], [“第 1 列”, “第 2 列”])
我的列表=[ {“example1”:{“subkey_example1”:{“ex1”:“2”,“ex2”:“4”},“example2”:{“subkey_example2”:{“ex3”:“1”,“ex4”: “3”}}}, “example3”:{“subkey_example3”:{“ex5”:“4”,“ex6”:“2”},“example4”:{“subkey_example4”:{“ex7”:“1”,“ex8”:“ 3"}}} ]
df = df.withColumn("column3", struct([col(f"value.{key}") for key in my_list[0].keys()]))
df.show(截断=False)