我正在尝试创建一个 DataFrame
来自 json 字符串(不是文件)的对象:
json_string = "[{'code': '8', 'name': 'Human'}, {'code': '11', 'name': 'Orc'}]"
df = pd.read_json(json_string)
但这种方法会导致以下错误:
ValueError: Expected object or value
documentation让它听起来像是可能的:
pandas.read_json(path_or_buf=None, orient=None, typ='frame', dtype=True, convert_axes=True, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=False, date_unit=None, encoding=None, lines=False, chunksize=None, compression='infer')
Convert a JSON string to pandas object
- path_or_buf : a valid JSON string or file-like, default: None The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file://localhost/path/to/table.json
我已经尝试使用
orient
的几种组合来调用该方法。没有一个成功。有关如何完成此操作的任何提示?我真的不希望将我的字符串保存到文件中的开销能够使用
read_json()
成功地。
最佳答案
您可以使用 eval
将字符串评估为 dict 然后直接传递给 DataFrame
构造函数。
>>> import pandas as pd
>>> pd.DataFrame(eval("[{'code': '8', 'name': 'Human'}, {'code': '11', 'name': 'Orc'}]"))
code name
0 8 Human
1 11 Orc
同样你也可以使用
ast.literal_eval
代替 eval
>>> import ast
>>> pd.DataFrame(ast.literal_eval("[{'code': '8', 'name': 'Human'}, {'code': '11', 'name': 'Orc'}]"))
code name
0 8 Human
1 11 Orc
关于python - Pandas read_json() 因一个简单的 JSON 字符串而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48593007/