Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add quotes " " to every element in non numeric column of a dataframe saved as CSV

Tags:

python

pandas

I have DataFrame

id,type,value
1,8,value1
2,2,value2
3,7,value3
4,3,value4
5,10,value5
6,3,value16

I want to add to the value id and value of the CSV file to be allocated quotes

"1",8,"value1"
"2",2,"value2"

What better way to do it

like image 913
Ekaterina Avatar asked Jan 31 '17 14:01

Ekaterina


People also ask

Why does my CSV file have quotes?

So quote characters are used in CSV files when the text within a field also includes a comma and could be confused as being the reserved comma delimiter for the next field. Quote characters indicate the start and end of a block of text where any comma characters can be ignored.


1 Answers

converting to strings and using +

df.update('"' + df[['id', 'value']].astype(str) + '"')
print(df)

using applymap

df.update(df[['id', 'value']].applymap('"{}"'.format))
print(df)

Both yield

    id  type      value
0  "1"     8   "value1"
1  "2"     2   "value2"
2  "3"     7   "value3"
3  "4"     3   "value4"
4  "5"    10   "value5"
5  "6"     3  "value16"
like image 62
piRSquared Avatar answered Sep 28 '22 08:09

piRSquared