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?
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.
You can convert the column “Fee” to a string by simply using DataFrame. apply(str) , for example df["Fee"]=df["Fee"]. apply(str) .
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With