How to specify column type(I need string) using pandas.to_csv method in Python?

3.2k views Asked by At
import pandas as pd
data = {'x':['011','012','013'],'y':['022','033','041']}
Df = pd.DataFrame(data = data,type = str)
Df.to_csv("path/to/save.csv")

There result I've obtained seems as this

1

There are 1 answers

0
zuku On

To achieve such result it will be easier to export directly to xlsx file, even without setting dtype of DataFrame.

import pandas as pd
writer = pd.ExcelWriter('path/to/save.xlsx')
data = {'x':['011','012','013'],'y':['022','033','041']}
Df = pd.DataFrame(data = data)
Df.to_excel(writer,"Sheet1")
writer.save()

I've tried also some other methods like prepending apostrophe or quoting all fields with ", but it gave no effect.