Python:如何使用dataframe.to_csv保持前导零 [英] Python: how to keep leading zeros with dataframe.to_csv

查看:1739
本文介绍了Python:如何使用dataframe.to_csv保持前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从txt文件读取数据后,出现如下数据帧(df1):

There is a dataframe (df1) like as following after I read the data from txt file:

 name   l1     l2
  a    00000  00000 
  b    00010  00002
  c    00000  01218

当我如下使用python代码时:

When I use the python code as following:

dataframe.to_csv('test.csv', index= False)

然后,我使用以下代码进行阅读:

Then I use the following code to read:

  df = pd.read_csv('test.csv')

我发现数据帧是df2,如下所示

I found the dataframe is being df2 as following

       name   l1      l2
        a      0       0
        b     10       2
        c      0      1218

但是我想像df1一样在数据帧中保留前导零.

But I want to keep the leading zero in the dataframe like df1.

谢谢!

推荐答案

前导零将被删除,因为Pandas会将这些值隐式转换为整数类型.您想将数据读取为字符串类型,可以通过指定dtype=str:

The leading zeros are being removed because Pandas is implicitly converting the values to integer types. You want to read the data as string types, which you can do by specifying dtype=str:

pd.read_csv('test.csv', dtype=str)

这篇关于Python:如何使用dataframe.to_csv保持前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆