Skip to content

Commit 86e47d3

Browse files
authored
REGR: read_fwf raising ValueError when widths was specified with usecols (#46691)
1 parent 9b4f03e commit 86e47d3

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
@@ -1354,7 +1354,8 @@ def read_fwf(
13541354
len_index = 1
13551355
else:
13561356
len_index = len(index_col)
1357-
if len(names) + len_index != len(colspecs):
1357+
if kwds.get("usecols") is None and len(names) + len_index != len(colspecs):
1358+
# If usecols is used colspec may be longer than names
13581359
raise ValueError("Length of colspecs must match length of names")
13591360

13601361
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)