Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quote only the required columns using pandas to_csv

I need to generate a csv using pandas to_csv function. I tried quote=csv.QUOTE_NONNUMERIC. But for one of the date time column I dont need double quotes.

Is there a way to select the columns for which we want double quotes?

like image 203
Sowmika Avatar asked Dec 05 '17 06:12

Sowmika


People also ask

What does to_csv do in pandas?

Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.

Does pandas to_csv overwrite?

When you write pandas DataFrame to an existing CSV file, it overwrites the file with the new contents. To append a DataFrame to an existing CSV file, you need to specify the append write mode using mode='a' .

What is to_csv in Python?

to_csv() function has converted the given Series object into a comma-separated format. Example #2: Use Series. to_csv() function to convert the given series object to csv format.

How do I convert a Pandas DataFrame to a CSV file?

Exporting the DataFrame into a CSV file Pandas 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.


1 Answers

Thanks people. I got the answer so just thought to share.

First I got the list of headers to be quoted and looped them something like below:

for col in quoteColumnsList:
    df[col] = '"' + df[col] + '"'

Here my quotechar is '"'. Now I used to_csv with quote parameter as csv.QUOTE_NONE. This way we get the double quotes only to the required columns.

like image 155
Sowmika Avatar answered Oct 06 '22 11:10

Sowmika