Skip to content

Commit 46fcc75

Browse files
Backport PR #46691: REGR: read_fwf raising ValueError when widths was specified with usecols (#46709)
Co-authored-by: Patrick Hoefler <[email protected]>
1 parent 63d2af5 commit 46fcc75

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

doc/source/whatsnew/v1.4.3.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ including other versions of pandas.
1414

1515
Fixed regressions
1616
~~~~~~~~~~~~~~~~~
17-
-
17+
- Fixed regression in :func:`read_fwf` raising ``ValueError`` when ``widths`` was specified with ``usecols`` (:issue:`46580`)
1818
-
1919

2020
.. ---------------------------------------------------------------------------

pandas/io/parsers/readers.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -867,7 +867,8 @@ def read_fwf(
867867
len_index = 1
868868
else:
869869
len_index = len(index_col)
870-
if len(names) + len_index != len(colspecs):
870+
if kwds.get("usecols") is None and len(names) + len_index != len(colspecs):
871+
# If usecols is used colspec may be longer than names
871872
raise ValueError("Length of colspecs must match length of names")
872873

873874
kwds["colspecs"] = colspecs

pandas/tests/io/parser/test_read_fwf.py

+23
Original file line numberDiff line numberDiff line change
@@ -930,3 +930,26 @@ def test_names_and_infer_colspecs():
930930
result = read_fwf(StringIO(data), skiprows=1, usecols=[0, 2], names=["a", "b"])
931931
expected = DataFrame({"a": [959.0], "b": 22.2})
932932
tm.assert_frame_equal(result, expected)
933+
934+
935+
def test_widths_and_usecols():
936+
# GH#46580
937+
data = """0 1 n -0.4100.1
938+
0 2 p 0.2 90.1
939+
0 3 n -0.3140.4"""
940+
result = read_fwf(
941+
StringIO(data),
942+
header=None,
943+
usecols=(0, 1, 3),
944+
widths=(3, 5, 1, 5, 5),
945+
index_col=False,
946+
names=("c0", "c1", "c3"),
947+
)
948+
expected = DataFrame(
949+
{
950+
"c0": 0,
951+
"c1": [1, 2, 3],
952+
"c3": [-0.4, 0.2, -0.3],
953+
}
954+
)
955+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)