Quote only the required columns using pandas to_csv
Asked Answered
R

2

7

I need to generate a csv using pandas to_csv function. I tried quote=csv.QUOTE_NONNUMERIC. But for one of the date time column I dont need double quotes.

Is there a way to select the columns for which we want double quotes?

Rastus answered 5/12, 2017 at 6:24 Comment(2)
You might want to tag this as python, too.Hemato
@Rastus Please share the dataframe sample(2-3) rows or df.dtypesDoodlebug
R
9

Thanks people. I got the answer so just thought to share.

First I got the list of headers to be quoted and looped them something like below:

for col in quoteColumnsList:
    df[col] = '"' + df[col] + '"'

Here my quotechar is '"'. Now I used to_csv with quote parameter as csv.QUOTE_NONE. This way we get the double quotes only to the required columns.

Rastus answered 6/12, 2017 at 3:34 Comment(1)
nice solution and simpleLew
T
0

This worked better for me:

columnsList = data.columns #(or specific columns that you need)
for col in columnsList:
   data[col] =  data[col].apply(lambda x: "" + str(x) + "")

Example: For my project, I had to add quotes and convert them to list.

def convert_list(data):
    columnsList = data.columns
    for col in columnsList :
        data[col] =  data[col].apply(lambda x: "" + str(x) + "") #this adds single quotes without specifying it as "'")
    df = data.values.tolist()
    return df
Tamarin answered 12/10, 2020 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.