将Pandas数据框转换为CSV字符串 [英] Convert Pandas dataframe to csv string
本文介绍了将Pandas数据框转换为CSV字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我要获取的示例:
Here is an example of what I am trying to get:
我有:
import pandas as pd
df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})
我的目标是:
',A,B\n0,0,1\n1,1,6\n'
我可以通过懒惰和恐怖来实现这一目标:
I can achieve this with lazy and horrible:
df.to_csv('temp.csv') # create unnecessary file
body = open('temp.csv').read()
另外,to_string()
方法看起来非常有前途;但是,我能想到的最好的方法是:
Also to_string()
methods looks very promising; however, the best I can come up with is this:
body = df.to_string()[1:].replace(' ', ',') + '\n'
这不会创建不必要的文件,但是看起来很草率,也许不是很可靠.
This does not create an unnecessary file, but seems sloppy and perhaps not very reliable.
我错过了一个更简单的解决方案吗?
Am I missing a simpler solution?
推荐答案
In [10]: df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})
In [11]: import io
In [12]: s = io.StringIO()
In [13]: df.to_csv(s)
In [14]: s.getvalue()
Out[14]: ',A,B\n0,0,1\n1,1,6\n'
这篇关于将Pandas数据框转换为CSV字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文