Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you switch single quotes to double quotes using to_tsv() when dealing with a column of lists?

Tags:

python

pandas

If I have a dataframe

df = pd.DataFrame({0: "text", 1: [["foo", "bar"]]})
df
      0           1
0  text  [foo, bar]

And I write the df out to a tsv file like this

df.to_csv('test.tsv',sep="\t",index=False,header=None, doublequote=True)

The tsv file looks like this

text    ['foo', 'bar']

How do I ensure there are double quotes around my list items and make test.tsv look like this?

text    ["foo", "bar"]
like image 828
solitaria Avatar asked Nov 06 '22 04:11

solitaria


1 Answers

Try with json.dumps

import json
df[1]=df[1].map(json.dumps)

Then

df.to_csv('test.tsv', sep="\t", index=False, header=None, doublequote=True, quoting=csv.QUOTE_NONE)
like image 175
BENY Avatar answered Nov 14 '22 23:11

BENY