Skip to content

Inconsistent behavior of read_csv when given an additional value on the first row of CSV file #33037

Closed
@tlorieul

Description

@tlorieul

Short description

Using the following invalid CSV:

col1_name,col2_name,col3_name
0,1,2,X
4,5,6,
6,7,8

It has 3 columns but the first row has 4 values and loading it should raise a ParsingError.

However, loading using:

pd.read_csv("test.csv", index_col=False)

does not raise any exception and returns the following DataFrame:

   col1_name  col2_name  col3_name
0          0          1          2
1          4          5          6
2          6          7          8

Thus, it silently drops the additional value X.

Problem description

This will happening if the first row and the following ones are invalid.
If the first invalid row is not the first row, it will throw a ParsingError exception.
I.e. the following CSV produces the same results (silently dropping additional value):

col1_name,col2_name,col3_name
0,1,2,X
4,5,6,X
6,7,8
col1_name,col2_name,col3_name
0,1,2,X
4,5,6,X
6,7,8,X
col1_name,col2_name,col3_name
0,1,2,X
4,5,6
6,7,8,X

But this, as expected, throws an exception:

col1_name,col2_name,col3_name
0,1,2
4,5,6,X
6,7,8,X

Finally, if there are two additional values instead of a single one, it throws the following exception:

IndexError: list index out of range

Having a consistent behavior by throwing an exception in every of the previous cases would be enjoyable.
The fact that it is silent make it harder to validate CSV files.

Expected Output

Throw a ParsingError in the previous cases.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.7.7.final.0
python-bits : 64
OS : Linux
OS-release : 4.15.0-91-generic
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.0.3
numpy : 1.18.1
pytz : 2019.3
dateutil : 2.8.1
pip : 20.0.2
setuptools : 46.1.1.post20200323
Cython : 0.29.15
pytest : 5.4.1
hypothesis : None
sphinx : 2.4.4
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.1
IPython : 7.13.0
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : 3.1.3
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pytest : 5.4.1
pyxlsb : None
s3fs : None
scipy : 1.4.1
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
numba : None

Edits

  • corrected copy-paste error in the returned DataFrame example (cf. reply by @gfyoung)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions