1

I have a pandas dataframe which is initially columns of type int. I change the type to string and then save it using to_csv. But in the csv I am saving, I am not getting data in the form '1', '2',.., instead its like 1,2,...

This is what I am doing:

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.random.randint(0,5,size=(3, 4)), columns=list('ABCD'))
>>> df
   A  B  C  D
0  2  3  0  4
1  4  0  3  4
2  4  4  4  3
>>> print(df.dtypes)
A    int64
B    int64
C    int64
D    int64
dtype: object
>>> df = df.astype(str)
>>> df
   A  B  C  D
0  2  3  0  4
1  4  0  3  4
2  4  4  4  3

>>> print(df.dtypes)
A    object
B    object
C    object
D    object
dtype: object
>>> df.to_csv('./df.csv', index = False)

When I check the saved file I get the following

➜ head -2 df.csv
A,B,C,D
2,3,0,4

I want it to be like the following:

➜ head -2 df.csv
A,B,C,D
"2","3","0","4"
2
  • You can just add the quoting param: df.to_csv('./df.csv', index=False, quoting=1) Commented Oct 21, 2019 at 14:51
  • And you don't want quotes around the header? Commented Oct 21, 2019 at 14:51

2 Answers 2

1

You can pass quoting to to_csv:

import csv
df.to_csv('a.csv', index=False,, quoting=csv.QUOTE_NONNUMERIC)

# or without importing csv module
df.to_csv('a.csv', index=False,, quoting=2)

You can even do with the original data frame with quoting=1:

df.to_csv('a.csv' quoting=1)

Output:

"A","B","C","D"
"2","3","0","4"
"4","0","3","4"
"4","4","4","3"
Sign up to request clarification or add additional context in comments.

Comments

0

This works

df = df.apply(lambda x: '"' + str(x) + '"')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.