usp*_*pow 11 python json pandas
我首先通过pandas read_csv()函数将CSV读入Pandas数据帧.既然数据在实际数据框中,我试着写这样的东西:
for row in df.iterrows():
    row[1].to_json(path_to_file)
这有效,但只有最后一行保存到磁盘,因为每次调用row [1] .to_json(path_to_file)时我都在重写文件.我已经尝试了一些其他文件处理选项但无济于事.任何人都可以对如何进行有所了解吗?
谢谢!
con*_*lee 28
要从数据框创建换行符分隔的json df,请运行以下命令
df.to_json("path/to/filename.json",
           orient="records",
           lines=True)
密切关注那些可选的关键字args!该lines选项已添加到熊猫中0.19.0.
Noa*_*oah 15
您可以将缓冲区传递到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'