Skip to content

ENH: Improve error message for header argument containing non int types. GH16338 #16351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.21.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ Indexing
I/O
^^^

- Bug in ``pd.read_csv()`` in which non integer values for the header argument generated an unhelpful / unrelated error message (:issue:`16338`)


Plotting
Expand Down
6 changes: 6 additions & 0 deletions pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,8 @@ def __init__(self, kwds):
# validate header options for mi
self.header = kwds.get('header')
if isinstance(self.header, (list, tuple, np.ndarray)):
if not all(map(is_integer, self.header)):
raise ValueError("header must be integer or list of integers")
if kwds.get('as_recarray'):
raise ValueError("cannot specify as_recarray when "
"specifying a multi-index header")
Expand All @@ -1184,6 +1186,10 @@ def __init__(self, kwds):
raise ValueError("index_col must only contain row numbers "
"when specifying a multi-index header")

# GH 16338
elif self.header is not None and not is_integer(self.header):
raise ValueError("header must be integer or list of integers")

self._name_processed = False

self._first_chunk = True
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/io/parser/header.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,3 +277,12 @@ def test_no_header(self):
tm.assert_index_equal(df.columns, Index(lrange(5)))

tm.assert_index_equal(df2.columns, Index(names))

def test_non_int_header(self):
# GH 16338
msg = 'header must be integer or list of integers'
data = """1,2\n3,4"""
with tm.assert_raises_regex(ValueError, msg):
self.read_csv(StringIO(data), sep=',', header=['a', 'b'])
with tm.assert_raises_regex(ValueError, msg):
self.read_csv(StringIO(data), sep=',', header='string_header')