Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas to_csv with quoting=3 (QUOTE_NONNUMERIC) doesn't work

Tags:

python

pandas

From the docs regarding to_csv() and others:

quoting : int, Controls whether quotes should be recognized. Values are taken from csv.QUOTE_* values. Acceptable values are 0, 1, 2, and 3 for QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONE, and QUOTE_NONNUMERIC, respectively.

Setting quoting=3 still does not quote strings even if they're not numeric, and libreoffice is constantly defaulting to splitting by spaces which I never realise until its too late. How can I write CSV, quoting strings with spaces correctly?

like image 427
jozxyqk Avatar asked Feb 16 '15 12:02

jozxyqk


People also ask

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 CSV Quote_minimal?

quoting - controls when quotes should be generated by the writer or recognized by the reader. It can take one of the following constants: csv. QUOTE_MINIMAL means add quote only when required, for example, when a field contains either the quotechar or the delimiter. This is the default.

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.


1 Answers

It seems like the value in the csv library has changed since these docs were written. Rather than use the magic number 3, use csv.QUOTE_NONNUMERIC to be safe...

>>> import csv
>>> csv.QUOTE_NONNUMERIC
2

In full:

table.to_csv("myfile.csv", quoting=csv.QUOTE_NONNUMERIC)
like image 146
jozxyqk Avatar answered Sep 20 '22 09:09

jozxyqk