我有一个Spark Dataframe(在Palantir Foundry),列有"c_温度".此列的每一行都包含一个JSON字符串,其架构如下:

{"TempCelsiusEndAvg":"24.33","TempCelsiusEndMax":"null","TempCelsiusEndMin":"null","TempCelsiusStartAvg":"22.54","TempCelsiusStartMax":"null","TempCelsiusStartMin":"null","TempEndPlausibility":"T_PLAUSIBLE","TempStartPlausibility":"T_PLAUSIBLE"}

我try 用以下代码提取新列"TempCelsiusEndAvg"和"TempCelsiusStartAvg"中的平均温度值(它们有时为"NULL",有时具有类似"24.33"的值):

from pyspark.sql import functions as F
from pyspark.sql.types import StringType

def flat_json(sessions_finished):
    df = sessions_finished
    df = df.withColumn("new_temperature", F.col('c_temperature').cast(StringType())
    df = df.withColumn("TempCelsiusEndAvg", F.get_json_object("c_Temperature", '$.TempCelsiusEndAvg'))
    df = df.withColumn("TempCelsiusStartAvg", F.get_json_object("c_Temperature", '$.TempCelsiusStartAvg'))
    return df

我想让新的栏目里充斥着这样的替身:

... +-----------------+-------------------+ ...
... |TempCelsiusEndAvg|TempCelsiusStartAvg| ...
... +-----------------+-------------------+ ...
... |            24.33|              22.54| ...
... +-----------------+-------------------+ ...
... |            29.28|              25.16| ...
... +-----------------+-------------------+ ...
... |             null|               null| ...
... +-----------------+-------------------+ ...

新的数据帧包含列,但它们只用空值填充.有人能帮我解决这个问题吗?

... +-----------------+-------------------+ ...
... |TempCelsiusEndAvg|TempCelsiusStartAvg| ...
... +-----------------+-------------------+ ...
... |             null|               null| ...
... +-----------------+-------------------+ ...
... |             null|               null| ...
... +-----------------+-------------------+ ...
... |             null|               null| ...
... +-----------------+-------------------+ ...

在这个帖子里还有一个 comments :[https://stackoverflow.com/questions/46084158/how-can-you-parse-a-string-that-is-json-from-an-existing-temp-table-using-pyspar],它描述了我的问题,但我不知道如何使用这些信息.

推荐答案

您不需要做任何事情,因为该列已经是一个 struct .您可以通过使用.访问这些列来创建它们

 df = df.withColumn("TempCelsiusEndAvg", F.col("c_temperature.TempCelsiusEndAvg"))
 df = df.withColumn("TempCelsiusStartAvg", F.col("c_temperature.TempCelsiusStartAvg"))

Python相关问答推荐

已安装' owiener ' Python模块,但在导入过程中始终没有名为owiener的模块

在Transformer中使用LabelEncoding的ML模型管道

pandas DataFrame中类型转换混乱

机器人与Pyton Minecraft服务器状态不和

Python中是否有方法从公共域检索搜索结果

在Python中为变量的缺失值创建虚拟值

试图找到Python方法来部分填充numpy数组

当使用keras.utils.Image_dataset_from_directory仅加载测试数据集时,结果不同

Python上的Instagram API:缺少client_id参数"

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

查找两极rame中组之间的所有差异

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

如何从pandas的rame类继承并使用filepath实例化

将JSON对象转换为Dataframe

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

Python中的变量每次增加超过1

如何从需要点击/切换的网页中提取表格?

如何排除prefecture_related中查询集为空的实例?

在matplotlib中使用不同大小的标记顶部添加批注

不允许 Select 北极滚动?