gpt4 book ai didi

python - 将数据框转换为 JSON(在 pyspark 中),然后选择所需的字段

转载 作者:太空狗 更新时间:2023-10-30 00:31:17 38 4
gpt4 key购买 nike

我是 Spark 的新手。我有一个包含一些分析结果的数据框。我将该数据框转换为 JSON,以便可以在 Flask 应用程序中显示它:

results = result.toJSON().collect()

我的 json 文件中的示例条目如下。然后我尝试运行 for 循环以获得特定结果:

{"userId":"1","systemId":"30","title":"interest"}

for i in results:
print i["userId"]

这根本不起作用,我收到如下错误:Python (json) : TypeError: expected string or buffer

我使用了 json.dumpsjson.loads 但仍然一无所获 - 我不断收到诸如字符串索引必须为整数之类的错误以及上述错误。

然后我尝试了这个:

  print i[0]

这给了我 json 中的第一个字符“{”而不是第一行。我真的不知道该怎么做,谁能告诉我哪里出错了?

非常感谢。

最佳答案

如果 result.toJSON().collect() 的结果是 JSON 编码的字符串,那么您可以使用 json.loads() 将其转换为字典。您遇到的问题是,当您使用 for 循环迭代 dict 时,您将获得 dict 的键。在您的 for 循环中,您将键视为一个 dict,而实际上它只是一个 string。试试这个:

# toJSON() turns each row of the DataFrame into a JSON string
# calling first() on the result will fetch the first row.
results = json.loads(result.toJSON().first())

for key in results:
print results[key]

# To decode the entire DataFrame iterate over the result
# of toJSON()

def print_rows(row):
data = json.loads(row)
for key in data:
print "{key}:{value}".format(key=key, value=data[key])


results = result.toJSON()
results.foreach(print_rows)


编辑: 问题是 collect返回一个 list,而不是一个 dict。我已经更新了代码。始终阅读文档。

collect() Return a list that contains all of the elements in this RDD.

Note This method should only be used if the resulting array isexpected to be small, as all the data is loaded into the driver’smemory.

EDIT2:我怎么强调都不为过,总是 read the docs.

EDIT3:here .

关于python - 将数据框转换为 JSON(在 pyspark 中),然后选择所需的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43232169/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com