python - Pandas Dataframe 到具有单独记录的 JSON 文件

标签 python pandas

我正在尝试将 Pandas Dataframe 中的数据转储到 JSON 文件中以导入到 MongoDB 中。我在文件中需要的格式在表单的每一行都有 JSON 记录:

{<column 1>:<value>,<column 2>:<value>,...,<column N>:<value>}

df.to_json(,orient='records') 接近结果,但所有记录都转储到单个 JSON 数组中。

关于从数据框中获取此结果的有效方法有什么想法吗?

更新:我想出的最佳解决方案如下:

dlist = df.to_dict('records')
dlist = [json.dumps(record)+"\n" for record in dlist]
open('data.json','w').writelines(dlist)

最佳答案

文档here ,有几个orient选项可以传递,你至少需要pandas 0.12

In [2]: df = DataFrame(np.random.randn(10,2),columns=list('AB'))

In [3]: df
Out[3]: 
          A         B
0 -0.350949 -0.428705
1 -1.732226  1.895324
2  0.314642 -1.494372
3 -0.492676  0.180832
4 -0.985848  0.070543
5 -0.689386 -0.213252
6  0.673370  0.045452
7 -1.403494 -1.591106
8 -1.836650 -0.494737
9 -0.105253  0.243730

In [4]: df.to_json()
Out[4]: '{"A":{"0":-0.3509492646,"1":-1.7322255701,"2":0.3146421374,"3":-0.4926764426,"4":-0.9858476787,"5":-0.6893856618,"6":0.673369954,"7":-1.4034942394,"8":-1.8366498622,"9":-0.1052531862},"B":{"0":-0.4287054732,"1":1.8953235554,"2":-1.4943721459,"3":0.1808322313,"4":0.0705432211,"5":-0.213252257,"6":0.045451995,"7":-1.5911060576,"8":-0.4947369551,"9":0.2437304866}}'

关于python - Pandas Dataframe 到具有单独记录的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19638014/

相关文章:

python - if 语句返回 false,而它为 true

python - Python 匹配字符串

python - 将存储为字符串的 hashID 列表转换为一列唯一值

python - 如果其他列满足条件,则将操作应用于 Pandas 列

python - 将逻辑值与 pandas/numpy 中的 NaN 进行比较

python - 使用 yum 时如何修复 "Bad interpreter"错误?

python - dunder方法中的平等

python - 如何使用 python 自动化 git push 进程?

python - 计算唯一对并将计数存储在矩阵中

python - 要 float 的 timedelta 对象