patternpythonCriticalCanonical
Writing a pandas DataFrame to CSV file
Viewed 0 times
csvdataframepandasfilewriting
Problem
I have a dataframe in pandas which I would like to write to a CSV file.
I am doing this using:
And getting the following error:
I am doing this using:
df.to_csv('out.csv')
And getting the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128)
- Is there any way to get around this easily (i.e. I have unicode characters in my data frame)?
- And is there a way to write to a tab delimited file instead of a CSV using e.g. a 'to-tab' method (that I don't think exists)?
Solution
To delimit by a tab you can use the
To use a specific encoding (e.g. 'utf-8') use the
In many cases you will want to remove the index and add a header:
sep argument of to_csv:df.to_csv(file_name, sep='\t')To use a specific encoding (e.g. 'utf-8') use the
encoding argument:df.to_csv(file_name, sep='\t', encoding='utf-8')In many cases you will want to remove the index and add a header:
df.to_csv(file_name, sep='\t', encoding='utf-8', index=False, header=True)Code Snippets
df.to_csv(file_name, sep='\t')df.to_csv(file_name, sep='\t', encoding='utf-8')df.to_csv(file_name, sep='\t', encoding='utf-8', index=False, header=True)Context
Stack Overflow Q#16923281, score: 1561
Revisions (0)
No revisions yet.