python - 将 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)
这似乎有很多啤酒花。有更快的方法吗?
解决方案
你真的不需要第二步和第三步,你可以在同一行中浓缩第一步和最后一步:
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)
推荐阅读
- mongoose - 猫鼬,尽管数据有效,但模式验证失败
- meteor-useraccounts - 将用户列表转储到网站?
- android - Android Studio Bug Gradle 同步失败:找不到 com.android.tools.build:gradle:3.1.3
- javascript - 选择 id 更新的监听事件
- python - 返回分组中最后出现的字符串的语法
- java - 如何使用变量,特别是不同类中的日期
- node.js - GitHub 安全警报
- linux - 获取 lsof 命令 Python 3.5 的输出
- python - (Python) 通过 Scrapy 与 Ajax 网页交互
- c++ - 如何在 C++ 中的 .h 文件中的类中定义结构