我想读取一个非常大的 csv(无法在 excel 中打开并轻松编辑),但在第 100,000 行附近的某处,有一行有一个额外的列导致程序崩溃。这一行是错误的,所以我需要一种方法来忽略它是一个额外的列的事实。大约有 50 列,因此对标题进行硬编码并使用名称或 usecols 是不可取的。我也可能会在其他 csv 中遇到这个问题并想要一个通用的解决方案。不幸的是,我在 read_csv 中找不到任何东西。代码就这么简单:
def loadCSV(filePath):
dataframe = pd.read_csv(filePath, index_col=False, encoding='iso-8859-1', nrows=1000)
datakeys = dataframe.keys();
return dataframe, datakeys
最佳答案
通过 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)
关于python - 坏数据上的 Pandas 数据帧 read_csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33440805/