Skip to content Skip to sidebar Skip to footer

How To Add Quotes " " To Every Element In Non Numeric Column Of A Dataframe Saved As Csv

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

Solution 1:

Convert you id column as a string column. Then use the appropriate arguments in function to_csv:

import csv
df.id = df.id.astype(str)
df.to_csv('test.txt', index=False, quotechar='"',
                      header=None, quoting=csv.QUOTE_NONNUMERIC)

csv.QUOTE_NONNUMERIC will apply quotes to all columns that are obviously non numeric like int or float.

Solution 2:

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

idtype      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"

Post a Comment for "How To Add Quotes " " To Every Element In Non Numeric Column Of A Dataframe Saved As Csv"