Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Pandas dataframe to csv string

Tags:

python

pandas

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:

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?

like image 537
Akavall Avatar asked Apr 22 '14 22:04

Akavall


People also ask

How do I write pandas DataFrame to CSV?

Exporting the DataFrame into a CSV filePandas DataFrame to_csv() function exports the DataFrame to CSV format. If a file argument is provided, the output will be the CSV file. Otherwise, the return value is a CSV format like string. sep: Specify a custom delimiter for the CSV output, the default is a comma.

How do you convert a DataFrame to a string in Python?

You can convert the column “Fee” to a string by simply using DataFrame. apply(str) , for example df["Fee"]=df["Fee"]. apply(str) .

What does to_csv return?

to_csv() function write the given series object to a comma-separated values (csv) file/format. Parameter : path_or_buf : File path or object, if None is provided the result is returned as a string.


1 Answers

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' 
like image 164
elyase Avatar answered Sep 24 '22 02:09

elyase