Skip to content

Commit 42c2c74

Browse files
Backport PR #36937 on branch 1.1.x: BUG: GH36928 Allow dict_keys to be used as column names by read_csv (#37078)
Co-authored-by: abmyii <[email protected]>
1 parent ac75f34 commit 42c2c74

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/source/whatsnew/v1.1.4.rst

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

1515
Fixed regressions
1616
~~~~~~~~~~~~~~~~~
17+
- Fixed regression in :func:`read_csv` raising a ``ValueError`` when ``names`` was of type ``dict_keys`` (:issue:`36928`)
1718
- Fixed regression where attempting to mutate a :class:`DateOffset` object would no longer raise an ``AttributeError`` (:issue:`36940`)
1819
- Fixed regression where :meth:`DataFrame.agg` would fail with :exc:`TypeError` when passed positional arguments to be passed on to the aggregation function (:issue:`36948`).
1920
- Fixed regression in :class:`RollingGroupby` with ``sort=False`` not being respected (:issue:`36889`)

pandas/io/parsers.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,9 @@ def _validate_names(names):
413413
if names is not None:
414414
if len(names) != len(set(names)):
415415
raise ValueError("Duplicate names are not allowed.")
416-
if not is_list_like(names, allow_sets=False):
416+
if not (
417+
is_list_like(names, allow_sets=False) or isinstance(names, abc.KeysView)
418+
):
417419
raise ValueError("Names should be an ordered collection.")
418420

419421

pandas/tests/io/parser/test_common.py

+12
Original file line numberDiff line numberDiff line change
@@ -2212,3 +2212,15 @@ def test_read_table_delim_whitespace_non_default_sep(all_parsers):
22122212
)
22132213
with pytest.raises(ValueError, match=msg):
22142214
parser.read_table(f, delim_whitespace=True, sep=",")
2215+
2216+
2217+
def test_dict_keys_as_names(all_parsers):
2218+
# GH: 36928
2219+
data = "1,2"
2220+
2221+
keys = {"a": int, "b": int}.keys()
2222+
parser = all_parsers
2223+
2224+
result = parser.read_csv(StringIO(data), names=keys)
2225+
expected = DataFrame({"a": [1], "b": [2]})
2226+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)