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

时间:2013-10-28 14:53:27

标签: 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)

2 个答案:

答案 0 :(得分: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}}'

答案 1 :(得分:0)

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

json.dumps(your_dictionary)