pandas & excel:在存储为字符串的数字中保留尾随零

gv8xihay  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(105)

我有一个小的Excel电子表格,我正在使用pandas包阅读Python脚本。有一列看起来像是一个数字(比如“1.10”),它被存储为字符串,当我在Python脚本中访问单元格时,它被提取为浮点数,尾部的零不存在:

0 Section    float  1.1
 0 Text       str    One
 1 Section    float  1.2
 1 Text       str    Two
 2 Section    float  1.3
 2 Text       str    Three
 3 Section    float  1.4
 3 Text       str    Four
 4 Section    float  1.5
 4 Text       str    Five
 5 Section    float  1.6
 5 Text       str    Six
 6 Section    float  1.7
 6 Text       str    Seven
 7 Section    float  1.8
 7 Text       str    Eight
 8 Section    float  1.9
 8 Text       str    Nine
 9 Section    float  1.1
 9 Text       str    Ten
10 Section    float  1.11
10 Text       str    Eleven

我创建了a gist with a small Python script and Excel spreadsheet来说明这个问题。
有人知道如何将这种类型的单元格提取为字符串并保留尾随的空格吗?

2izufjch

2izufjch1#

可能的解决方案:

df = pd.read_excel('/tmp/numbers-as-strings.xlsx', dtype={'Section': str})

输出:

Section    Text
0      1.1     One
1      1.2     Two
2      1.3   Three
3      1.4    Four
4      1.5    Five
5      1.6     Six
6      1.7   Seven
7      1.8   Eight
8      1.9    Nine
9     1.10     Ten
10    1.11  Eleven

相关问题