Home > database >  Is there a way to enclose all values with double quotes when export to csv with Pandas? (But not col
Is there a way to enclose all values with double quotes when export to csv with Pandas? (But not col

Time:09-25

I want to be able to enclose all values when exporting to csv with double quotes but not enclose the column names with double quotes. I want to use the pandas library for the export to csv.

This is my current output

"Col1","Col2"
"val1","10"
"val2","15"
"val3","14"

This is what I want my output to be

Col1,Col2
"val1","10"
"val2","15"
"val3","14"

Does anyone know how to do this?

Thanks

CodePudding user response:

One approach is to write the header & rows separately.

import pandas as pd
import csv

df = pd.DataFrame({'col1': ['val1','val2','val3','val4'], 'col2': ['val1','val2','val3','val4']})

with open('filename.csv', 'w') as f:
    header_writer = csv.writer(f, delimiter=',', quoting=csv.QUOTE_NONE)
    header_writer.writerow(df.columns) 
    df.to_csv(f, sep=',', header=False, quoting=csv.QUOTE_ALL, index=None)

CodePudding user response:

You can try with regex,here is the example.

import re
import pandas as pd
df = pd.DataFrame({
    'Col1':['A','B'],
    'Col2':['C','D']
})
for column in df.columns:
    df[column] = df[column].apply(lambda x: f'"{x}"')
text = df.to_csv(index=None)
text = re.sub('" ','"',text)
print(text)

Output:

Col1,Col2
"A","C"
"B","D"
  • Related