首页 > 解决方案 > 将 JSON 格式的字符串导入 numpy.recarray 的最快方法?

问题描述

考虑这个 JSON 格式的字符串:

json_string = '{"SYM": ["this_string","this_string","this_string"],"DATE": ["NaN","NaN","NaN"],"YEST": ["NaN","NaN","NaN"],"other_DATE": ["NaN","NaN","NaN"],"SIZE": ["NaN","NaN","NaN"],"ACTIVITY": ["2019-09-27 14:18:28.000700 UTC","2019-09-27 14:18:28.000700 UTC","2019-09-27 14:18:28.000600 UTC"]}'

我可以将它导入到 numpy.recarray 执行以下操作:

result      = ast.literal_eval(json_string)
names       = list(result.keys())
formats     = ['O'] * len(names)
dtype       = dict(names = names, formats=formats)
array       = numpy.array(result.items(), dtype=dtype)

这似乎有很多啤酒花。有更快的方法吗?

标签: pythonjsonnumpy

解决方案


你真的不需要第二步和第三步,你可以在同一行中浓缩第一步和最后一步:

array = numpy.array(ast.literal_eval(json_string).items(), dtype=dtype)

也就是说,我会使用该json模块而不是ast.literal_eval因为literal_eval对于像{"FOO": [null, NaN]}.

import json
numpy.array(json.loads(json_string).items(), dtype=dtype)

推荐阅读