2

我正在尝试将 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)
4

2 回答 2

1

docs 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}}'
于 2013-10-28T15:50:15.987 回答
0

根据您的喜好在 python 字典中格式化您的数据并使用 simplejson:

json.dumps(your_dictionary)
于 2013-10-28T14:57:53.780 回答