将Pandas DataFrame写入换行符分隔的JSON [英] Write Pandas DataFrame to newline-delimited JSON
本文介绍了将Pandas DataFrame写入换行符分隔的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我首先通过pandas read_csv()函数将CSV读取到Pandas Data Frame中.现在数据已经在实际的数据帧中,我尝试编写如下代码:
I started by reading a CSV into a Pandas Data Frame via the pandas read_csv() function. Now that the data is in an actual data frame, I tried to write something like this:
for row in df.iterrows():
row[1].to_json(path_to_file)
这有效,但仅将最后一行保存到磁盘,因为每次调用row [1] .to_json(path_to_file)时我都在重写文件.我尝试了其他一些文件处理选项,但无济于事.任何人都可以对如何进行了解吗?
This works but only the last row is saved to disk because I've been rewriting the file each time I make a call to row[1].to_json(path_to_file). I've tried a few other file handling options but to no avail. Can anyone shed some insight on how to proceed?
谢谢!
推荐答案
您可以将缓冲区传递到df.to_json()
:
You can pass a buffer in to df.to_json()
:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame({"a":[1,3,5], "b":[1.1,1.2,1.2]})
In [3]: df
Out[3]:
a b
0 1 1.1
1 3 1.2
2 5 1.2
In [4]: f = open("temp.txt", "w")
In [5]: for row in df.iterrows():
row[1].to_json(f)
f.write("\n")
...:
In [6]: f.close()
In [7]: open("temp.txt").read()
Out[7]: '{"a":1.0,"b":1.1}\n{"a":3.0,"b":1.2}\n{"a":5.0,"b":1.2}\n'
这篇关于将Pandas DataFrame写入换行符分隔的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文