【问题标题】:ValueError: cannot convert float NaN to integer at read excelValueError:无法在读取 excel 时将浮点 NaN 转换为整数
【发布时间】:2021-04-28 08:29:55
【问题描述】:

我正在读取一个 xlsx 文件,每次我尝试打开它时都会弹出一个带有消息的窗口:

我们发现“...xlsx”中的某些内容存在问题。你想让我们尽可能多地恢复吗?如果您信任此工作簿的来源,请单击是

我试过用pandas打开文件如下::

df = pd.read_excel(path_xlsx)

或

df = pd.read_excel(path_xlsx, dtype=str)


>>ValueError: cannot convert float NaN to integer

我怀疑有问题的列是一个名为“ExpDate”的列...它包含这种样式的数据:

NaN
NaN
NaN
31/12/2021
31/12/2021
NaN

我无法手动操作文件

【问题讨论】:

  • 我们需要一些数据来重现这个。
  • 下载失败。
  • NaN 表示“非数字”。您正在尝试将其转换为数字。它应该怎么做?
  • API 应该将列转换为 str .. 我不想将日期转换为整数,但我无法手动操作文件

标签: python pandas


【解决方案1】:

很有趣!

即使 parse_dates 设置为 False,它仍然会尝试解析日期,并且主要是由 excel 中设置的列类型驱动的。一种方法是,如果任何日期列存在问题或您怀疑任何日期列存在问题,请在要求 pandas 阅读之前将该列更改为 excel 中的文本。

import pandas as pd
file_name="Inventory Lots_20210423142831(1).xlsx"
df=pd.read_excel(file_name,header=0,parse_dates=False)

解决方法关于这个问题,请清理dataclean up中的日期 然后通过 pandas 导入。

结果: Result

异常跟踪:

67                     cell_contents = xldate.xldate_as_datetime(cell_contents, epoch1904)
# then python3.8/site-packages/xlrd/xldate.py in xldate_as_datetime(xldate, datemode)
    150     # The integer part of the Excel date stores the number of days since
    151     # the epoch and the fractional part stores the percentage of the day.
--> 152     days = int(xldate)

【讨论】:

  • 脚本自动进入Wams,下载文件并打开。我无法手动操作 excel
猜你喜欢
  • 2020-08-14
  • 1970-01-01
  • 2020-04-10
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 2018-04-30
  • 1970-01-01
相关资源
最近更新 更多