如何在Python中使用pandas.to_csv方法指定列类型(我需要字符串)?

时间:2015-06-12 16:11:54

标签: pandas fieldtype

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 个答案:

答案 0 :(得分:0)

要实现这样的结果,即使不设置数据框的dtype,也可以更轻松地直接导出到xlsx文件。

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()

我还尝试过其他一些方法,例如预先添加撇号或用"引用所有字段,但它没有效果。