如果csv中缺少某些字段,如何让pandas抛出异常(或者注意)?

2024-06-01 01:30:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python阅读pandas的csv文件。当pandas在文件中的字段数比预期的要少时,就在文件中用不到预期的字段数填充。相反,我希望抛出一个异常。在

例如,如果我有这样一个CSV文件:

A, B, C
1, 2, 3
4,,6
5

对于熊猫,我可以这样读这个文件:

^{pr2}$

我想让熊猫在最后一行出错。这一行应该还有两个逗号(5,,)。缺少的逗号表示缺少的字段。在

除了pandas忽略缺少的逗号之外,有没有一种方法可以检测到这种情况并抛出异常?在

谢谢!在


Tags: 文件csv方法pandas情况逗号pr2少时
1条回答
网友
1楼 · 发布于 2024-06-01 01:30:07

documentation

error_bad_lines设置为False

error_bad_lines : boolean, default True
Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these “bad lines” will dropped from the DataFrame that is returned. (Only valid with C parser)

warn_bad_lines设置为True

^{pr2}$

这将为dataframe上的每一个错误行输出一个警告,而不是忽略它的存在或根本不返回dataframe

相关问题 更多 >