-3

I try to export a dataframe to a csv file by applying the following code line:

df.to_csv('df.csv', sep=';', encoding='latin-1', decimal=',')

Unfortunately I get the following error:

UnicodeEncodeError: 'latin-1' codec can't encode character '\u0131' in position 25: ordinal not in range(256)

How should I change my code? What would be the solution?

  • 2
    Could you also add a sample and reproducible copy for your dataframe so we get a better idea of the values, and what may be causing the issue. https://stackoverflow.com/questions/52413246/how-to-provide-a-reproducible-copy-of-your-dataframe-with-to-clipboard – JamesArthur Jul 17 '21 at 17:08
  • Have you checked this post?? https://stackoverflow.com/questions/3942888/unicodeencodeerror-latin-1-codec-cant-encode-character – Abhishek Parikh Jul 17 '21 at 17:15
  • It's because of the character \u0131 I guess. If I change my code to df.to_csv('df.csv', sep=';', decimal=',') I get no error, but the problem is that the conent looks weird then. – Economist Learning Python Jul 17 '21 at 17:15
  • @AbhishekParikh Yes exactly ty, but I dont exactly know how to change the code line df.to_csv('df.csv', sep=';', encoding='latin-1', decimal=',') – Economist Learning Python Jul 17 '21 at 17:16
  • You can use cp1252 for encoding – Abhishek Parikh Jul 17 '21 at 17:22
  • @AbhishekParikh Ty I tried df.to_csv('df.csv', sep=';', encoding='cp1252', decimal=',') but now I get the error UnicodeEncodeError: 'charmap' codec can't encode character '\u0131' in position 25: character maps to – Economist Learning Python Jul 17 '21 at 17:25

1 Answers1

0

Ok, I found the answer, the right code line looks as follows:

df.to_csv('df.csv', sep=';', encoding='utf-8-sig', decimal=',')

If you don't use utf-8-sig German Excel doesn't open the csv file properly.