Search code examples
pythoncsvpandasexport-to-csv

CSV dialect in pandas DataFrame to_csv (python)


I'm happy to use csv.Dialect objects for reading and writing CSV files in python. My only problem with this now is the following:

  • it seems like I can't use them as a to_csv parameter in pandas
  • to_csv and Dialect (and read_csv) parameters are different (eg. to_csv have sep instead of delimiter)... so generating a key-value parameterlist doesn't seem to be a good idea

So I'm a little lost here, what to do.

What can I do if I have a dialect specified but I have a pandas.DataFrame I have to write into CSV? Should I create a parameter mapping by hand?! Should I change to something else from to_csv?

I have pandas-0.13.0.


Note: to_csv(csv.reader(..., dialect=...), ...) didn't work:

need string or buffer, _csv.writer found


Solution

  • If you have a CSV reader, than you don't need to also do a pandas.read_csv call. You can create a dataframe with a dictionary, so your code would look something like:

    csv_dict = # Insert dialect code here to read in the CSV as a dictonary of the format {'Header_one': [1, 2, 3], 'Header_two': [4, 5, 6]}
    df = pd.DataFrame(csv_dict)