【问题标题】:Unable to read excel with leading zero in pandas无法读取熊猫中前导零的excel
【发布时间】:2026-01-20 12:55:01
【问题描述】:

如果我阅读 excel,它会被阅读为

   SKU Code Location Code  GIT
    123456           100   10
    123456           200   20
    123456           300    0

但实际上我的excel数据是

   SKU Code Location Code  GIT
    123456           0100   10
    123456           0200   20
    123456           0300    0

我已经尝试了以下

gitDataDF = pd.read_excel("filename.xlsx",
                           sheet_name='Sheet1', inferSchema='true'
                          ,converters={'Location Code': str})

gitDataDF = pd.read_excel("filename.xlsx",
                           sheet_name='Sheet1', inferSchema='true'
                          ,dtype={'Location Code': np.str})

更新 1: 值的长度不是固定的。可能是“N”

我应该怎么做才能阅读。你能帮我解决这个问题吗?

供您参考,我正在使用 Python 版本 - 3.8

熊猫版本 - 1.0.5

【问题讨论】:

  • 对我来说工作得很好,一个想法 - 列中的数据是否像 excel 中的零字符串?
  • 不,它是数字数据类型@jezrael
  • 所以如果excel中有数字,就没有零。

标签: python python-3.x excel pandas dataframe


【解决方案1】:

您可以尝试使用 f 字符串:

gitDataDF = pd.read_excel("filename.xlsx",
                           sheet_name='Sheet1', inferSchema='true'
                          ,converters={'Location Code': lambda x: f'{x:04}'})

【讨论】:

  • @T.SURESH ARUNACHALAM 哦,我明白了。您是否尝试过使用 dtype 而不是转换器?