微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python读取excel中的大整数

如何解决python读取excel中的大整数

我有一个带有以下 3 个大整数的 excel(实际上,它们是 id)。 但在excel中,它将以科学模式存储。 当我使用pandas读取excel时,由于整数太大,int64无法存储它,我会失去精度。

示例数据:(1.xlsx)
76307016609101000000000000000000
86412903902869300000000000000000
35575701294198100000000000000000

A = pd.read_excel("1.xlsx",engine="openpyxl",header=None,dtype=np.float64) 
% no matter what the dtype is the result will be wrong

print(int(A.loc[0])) # 76307016609101001211632066494464 wrong

不知道有没有比 int64 长的 int 类型,numpy/pandas 支持的。非常感谢!!

解决方法

如果你可以让 excel 吐出原始数字,那么你可以通过将数字读取为文本来解决这个问题

import pandas as pd 
import io

txt='''\
line,Num,text
1,12345678901234435346789012345678901234567890,"large"
2,66464644666669999999999999999999999999999999999999999999999999999999999999991,"larger"
3,1,"unity"
4,-9999999999999999999999999999999999999999,"larger in a different way"
'''

df=pd.read_csv(io.StringIO(txt),converters={'Num':int})

print(df)

结果

   line                                                Num  \
0     1       12345678901234435346789012345678901234567890   
1     2  6646464466666999999999999999999999999999999999...   
2     3                                                  1   
3     4          -9999999999999999999999999999999999999999   

                        text  
0                      large  
1                     larger  
2                      unity  
3  larger in a different way  

你仍然可以对它们进行求和

n=df["Num"][1]
print (n,n+1 )

收益

66464644666669999999999999999999999999999999999999999999999999999999999999991 
66464644666669999999999999999999999999999999999999999999999999999999999999992

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。