我有一个包含自定义格式#0000000000的列的EXCEL文件.如果我使用这三个命令中的任何一个将其读入Pandas 数据框中

pd.read_excel("F或matted_File.xlsx", dtype=str)

pd.read_excel("F或matted_File.xlsx", dtype="object")

或 just

pd.read_excel("F或matted_File.xlsx")

我得到了一个截断为零的数据.

Without going into details, but let's assume I cannot change the Custom F或matting of the input Excel file. How can I preserve the leading zeros while reading the file to pandas data frame?

推荐答案

您不能像读取Pandas时那样读取显示的值(openpyxl可能是可能的),因为值被存储为数字(1,2,3,...),但列具有定制格式(#0000000000).

enter image description here

import pandas as pd
df = pd.read_excel('data.xlsx', dtype={'UID': str})
print(df)

# Output
   UID
0    1
1    2
2    3
3    4
4    5
5    6
6    7
7    8
8    9
9   10

您可以使用str.zfill重新创建列格式:

df['UID'] = df['UID'].str.zfill(10)
print(df)

# Output
          UID
0  0000000001
1  0000000002
2  0000000003
3  0000000004
4  0000000005
5  0000000006
6  0000000007
7  0000000008
8  0000000009
9  0000000010

Python相关问答推荐

pyautogui.locateOnScreen在Linux上的工作方式有所不同

如何用symy更新分段函数

将HLS纳入媒体包

对Numpy函数进行载体化

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

基于字符串匹配条件合并两个帧

如果值发生变化,则列上的极性累积和

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

Stacked bar chart from billrame

如何在Polars中从列表中的所有 struct 中 Select 字段?

基于形状而非距离的两个numpy数组相似性

如何杀死一个进程,我的Python可执行文件以sudo启动?

ruamel.yaml dump:如何阻止map标量值被移动到一个新的缩进行?

Python—压缩叶 map html作为邮箱附件并通过sendgrid发送

OpenGL仅渲染第二个三角形,第一个三角形不可见

Python pint将1/华氏度转换为1/摄氏度°°

Beautifulsoup:遍历一个列表,从a到z,并解析数据,以便将其存储在pdf中.

如何在Python 3.9.6和MacOS Sonoma 14.3.1下安装Pyregion

如何将一组组合框重置回无 Select tkinter?

为罕见情况下的回退None值键入