Skip to content

BUG: read_fwf raise if len colspec doesnt match len names #42920

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 10 commits into from
Aug 31, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ I/O
- Bug in :func:`read_excel` attempting to read chart sheets from .xlsx files (:issue:`41448`)
- Bug in :func:`json_normalize` where ``errors=ignore`` could fail to ignore missing values of ``meta`` when ``record_path`` has a length greater than one (:issue:`41876`)
- Bug in :func:`read_csv` with multi-header input and arguments referencing column names as tuples (:issue:`42446`)
-
- Bug in :func:`read_fwf` where difference in length of ``colspecs`` and ``names`` did not throw any error (:issue:`40830`)

Period
^^^^^^
Expand Down
20 changes: 20 additions & 0 deletions pandas/io/parsers/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,26 @@ def read_fwf(
colspecs.append((col, col + w))
col += w

# GH#40830
# Ensure length of `colspecs` matches length of `names`
names = kwds.get("names")
if names is not None:
if len(names) != len(colspecs):
# maybe name of index(s) not present in `names`
len_index = 0
if kwds.get("index_col") is not None:
index_col = kwds.get("index_col")
if isinstance(index_col, int) or isinstance(index_col, str):
len_index = 1
elif index_col is False:
len_index = 0
else:
# error: Argument 1 to "len" has incompatible type
# "Optional[Any]"; expected "Sized" [arg-type]
len_index = len(index_col) # type: ignore[arg-type]
if len(names) + len_index != len(colspecs):
raise ValueError("Length of colspecs must match length of names")

kwds["colspecs"] = colspecs
kwds["infer_nrows"] = infer_nrows
kwds["engine"] = "python-fwf"
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/io/parser/test_read_fwf.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,3 +710,20 @@ def test_encoding_mmap(memory_map):
data.seek(0)
df_reference = DataFrame([[1, "A", "Ä", 2]])
tm.assert_frame_equal(df, df_reference)


@pytest.mark.parametrize(
"colspecs, names, widths",
[
([(0, 6), (6, 12), (12, 18), (18, None)], list("abcde"), None),
([6] * 4, list("abcde"), None),
(None, list("abcde"), [6] * 4),
],
)
def test_len_colspecs_len_names(colspecs, names, widths):
# GH#40830
data = """col1 col2 col3 col4
bab ba 2"""
msg = "Length of colspecs must match length of names"
with pytest.raises(ValueError, match=msg):
read_fwf(StringIO(data), colspecs=colspecs, names=names, widths=widths)