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

扶醉桌前 提交于 2020-01-07 06:20:28

问题


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:


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.



来源:https://stackoverflow.com/questions/30807676/how-to-specify-column-typei-need-string-using-pandas-to-csv-method-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!