Python 将 Pandas 数据框转换为 csv 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23231605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:33:07  来源:igfitidea点击:

Convert Pandas dataframe to csv string

pythonpandas

提问by Akavall

Here is an example of what I am trying to get:

这是我想要得到的一个例子:

I have:

我有:

import pandas as pd 
df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})

My goal is:

我的目标是:

',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()

Also to_string()methods looks very promising; however, the best I can come up with is this:

此外to_string()方法看起来非常有前途; 然而,我能想到的最好的是:

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?

我错过了一个更简单的解决方案吗?

采纳答案by Jeff

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'

回答by elyase

The simplest way is just to not input any filename, in this case a string is returned:

最简单的方法是不输入任何文件名,在这种情况下返回一个字符串:

>>> df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})
>>> df.to_csv()
',A,B\n0,0,1\n1,1,6\n'