23

I have read the manual here and saw this answer, but it is not working:

>>> import pandas as pd
>>> import csv
>>> pd.Series([my_list]).to_csv('output.tsv',sep='\t',index=False,header=False, quoting=csv.QUOTE_NONE)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: to_csv() got an unexpected keyword argument 'quoting'

Without the quoting argument, it works.

pd.Series([my_list]).to_csv('output.tsv',sep='\t',index=False,header=False)

But this is incompatible with my intended usage.

To make things even more confusing, when I wrote out a table this way, there were no quotes, and no errors:

my_dataframe.to_csv('output2.tsv',sep='\t', quoting=csv.QUOTE_NONE)

Any idea what is going on?

Community
  • 1
  • 1
user5359531
  • 3,217
  • 6
  • 30
  • 55
  • 1
    According to the [docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_csv.html) there is no `quoting` argument to Series.to_csv, so it's not surprising you are getting that error. Is there a reason you can't just use a `DataFrame`? – juanpa.arrivillaga Jul 15 '16 at 23:53
  • I was just trying to write out a single column of data and thought I could avoid unnecessary conversion steps. Looks like the conversion to `DataFrame` is necessary after all. No big deal, I will just do that instead. Thanks. – user5359531 Jul 18 '16 at 14:39

1 Answers1

22

The internal pandas implementation of Series.to_csv() first converts Series to DataFrame and then calls DataFrame.to_csv() method:

def to_csv(self, path, index=True, sep=",", na_rep='', float_format=None,
           header=False, index_label=None, mode='w', nanRep=None,
           encoding=None, date_format=None, decimal='.'):
    """
    Write Series to a comma-separated values (csv) file
    ...
    """
    from pandas.core.frame import DataFrame
    df = DataFrame(self)
    # result is only a string if no path provided, otherwise None
    result = df.to_csv(path, index=index, sep=sep, na_rep=na_rep,
                       float_format=float_format, header=header,
                       index_label=index_label, mode=mode, nanRep=nanRep,
                       encoding=encoding, date_format=date_format,
                       decimal=decimal)
    if path is None:
        return result

So you can convert it yourself and then you will have a richer set of parameters:

pd.DataFrame(your_series_obj).to_csv(..., quoting=csv.QUOTE_NONE)

or:

your_series_obj.to_frame().to_csv(..., quoting=csv.QUOTE_NONE)
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419