简体   繁体   中英

Python Pandas: How to replace to_csv string quoting from double quotes to single quotes

I have a dataframe where one of the column(col2) has many commas hence when pandas output to a CSV file, it by defaults encloses that field value in double quotes. How do i specify that i want single quotes for columns with commas?

df:

col1  col2     col3
1    x;y,b;c  blabla

df.to_csv('myfile.csv')

current CSV file:

col1,col2,col3
 1,"x;y,b;c",blabla

I want single quotes instead:

col1,col2,col3
 1,'x;y,b;c',blabla

you can use quotechar="'" parameter:

In [41]: df
Out[41]:
   col1     col2    col3
0     1  x;y,b;c  blabla

In [42]: print(df.to_csv(index=False, quotechar="'"))
col1,col2,col3
1,'x;y,b;c',blabla

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM