Skip to content
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.4.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ including other versions of pandas.

Fixed regressions
~~~~~~~~~~~~~~~~~
-
- Fixed regression in :func:`read_fwf` raising ``ValueError`` when ``widths`` was specified with ``usecols`` (:issue:`46580`)
-

.. ---------------------------------------------------------------------------
Expand Down
3 changes: 2 additions & 1 deletion pandas/io/parsers/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -867,7 +867,8 @@ def read_fwf(
len_index = 1
else:
len_index = len(index_col)
if len(names) + len_index != len(colspecs):
if kwds.get("usecols") is None and len(names) + len_index != len(colspecs):
# If usecols is used colspec may be longer than names
raise ValueError("Length of colspecs must match length of names")

kwds["colspecs"] = colspecs
Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/io/parser/test_read_fwf.py
Original file line number Diff line number Diff line change
Expand Up @@ -930,3 +930,26 @@ def test_names_and_infer_colspecs():
result = read_fwf(StringIO(data), skiprows=1, usecols=[0, 2], names=["a", "b"])
expected = DataFrame({"a": [959.0], "b": 22.2})
tm.assert_frame_equal(result, expected)


def test_widths_and_usecols():
# GH#46580
data = """0 1 n -0.4100.1
0 2 p 0.2 90.1
0 3 n -0.3140.4"""
result = read_fwf(
StringIO(data),
header=None,
usecols=(0, 1, 3),
widths=(3, 5, 1, 5, 5),
index_col=False,
names=("c0", "c1", "c3"),
)
expected = DataFrame(
{
"c0": 0,
"c1": [1, 2, 3],
"c3": [-0.4, 0.2, -0.3],
}
)
tm.assert_frame_equal(result, expected)