TypeError:没有'nan_inf_to_errors' Workbook() 选项的 write_number() 不支持 NAN/INF
Posted
技术标签:
【中文标题】TypeError:没有\'nan_inf_to_errors\' Workbook() 选项的 write_number() 不支持 NAN/INF【英文标题】:TypeError: NAN/INF not supported in write_number() without 'nan_inf_to_errors' Workbook() optionTypeError:没有'nan_inf_to_errors' Workbook() 选项的 write_number() 不支持 NAN/INF 【发布时间】:2021-03-24 11:23:58 【问题描述】:我想将尺寸为 (3960, 225) 的 X (ndarray) 保存在 excel 文件 (.xlsx) 中。在 X 中,我有一些缺失值 (nan)。我为它做了一个代码。但是,我得到了错误。
代码如下:
workbook = xlsxwriter.Workbook('arrays.xlsx')
worksheet = workbook.add_worksheet()
row = 0
for col, data in enumerate(X):
worksheet.write_column(row, col, data)
workbook.close()
df = pd.DataFrame(X)
## save to xlsx file
filepath = 'my_excel_file.xlsx'
df.to_excel(filepath, index=False)
这是回溯:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm 2020.2.1\plugins\python\helpers\pydev\pydevd.py", line 1448, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm 2020.2.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/Nafees Ahmed/PycharmProjects/Extra_Sensory_Experimetns/main.py", line 475, in <module>
worksheet.write_column(row, col, data)
File "C:\Users\Nafees Ahmed\AppData\Local\Programs\Python\Python38\lib\site-packages\xlsxwriter\worksheet.py", line 69, in cell_wrapper
return method(self, *args, **kwargs)
File "C:\Users\Nafees Ahmed\AppData\Local\Programs\Python\Python38\lib\site-packages\xlsxwriter\worksheet.py", line 1164, in write_column
error = self._write(row, col, token, cell_format)
File "C:\Users\Nafees Ahmed\AppData\Local\Programs\Python\Python38\lib\site-packages\xlsxwriter\worksheet.py", line 481, in _write
return self._write_number(row, col, *args)
File "C:\Users\Nafees Ahmed\AppData\Local\Programs\Python\Python38\lib\site-packages\xlsxwriter\worksheet.py", line 589, in _write_number
raise TypeError(
TypeError: NAN/INF not supported in write_number() without 'nan_inf_to_errors' Workbook() option
也许是因为 nan(缺失)值。有没有简单的方法来处理这个错误?
【问题讨论】:
【参考方案1】:用零填充NaN
值,并不能解决问题,如果你想将NaN
值保持为NaN
,你应该跳过这样的填充值:
row = 0
for col, data in enumerate(X):
try:
worksheet.write_column(row, col, data)
except:
pass
【讨论】:
我正在标记您的答案,这将使您的个人资料覆盖,您将能够在此平台上提出更多问题。请标记我的问题并回答。【参考方案2】:你可以使用pandas的@987654321@方法。
df.fillna(0)
会将所有NaN
替换为0.0
【讨论】:
【参考方案3】:我使用以下代码填写了非:
X[np.isnan(X)] = 0.;
【讨论】:
以上是关于TypeError:没有'nan_inf_to_errors' Workbook() 选项的 write_number() 不支持 NAN/INF的主要内容,如果未能解决你的问题,请参考以下文章
Python - TypeError: '...' 类型的对象没有 len()
TypeError: DisplayMarketingMessage() 没有参数如何解决它