Skip to content

BUG: read_csv raising if parse_dates is used with MultiIndex columns #44408

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 2 commits into from
Nov 14, 2021
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,7 @@ I/O
- Bug in :func:`json_normalize` where multi-character ``sep`` parameter is incorrectly prefixed to every key (:issue:`43831`)
- Bug in :func:`read_csv` with :code:`float_precision="round_trip"` which did not skip initial/trailing whitespace (:issue:`43713`)
- Bug in dumping/loading a :class:`DataFrame` with ``yaml.dump(frame)`` (:issue:`42748`)
- Bug in :func:`read_csv` raising ``ValueError`` when ``parse_dates`` was used with ``MultiIndex`` columns (:issue:`8991`)
-

Period
Expand Down
11 changes: 8 additions & 3 deletions pandas/io/parsers/base_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,8 @@ def _validate_parse_dates_presence(self, columns: list[str]) -> None:
# ParseDates = Union[DateGroups, List[DateGroups],
# Dict[ColReference, DateGroups]]
cols_needed = itertools.chain.from_iterable(
col if is_list_like(col) else [col] for col in self.parse_dates
col if is_list_like(col) and not isinstance(col, tuple) else [col]
for col in self.parse_dates
)
else:
cols_needed = []
Expand Down Expand Up @@ -1091,7 +1092,7 @@ def _isindex(colspec):
if isinstance(parse_spec, list):
# list of column lists
for colspec in parse_spec:
if is_scalar(colspec):
if is_scalar(colspec) or isinstance(colspec, tuple):
if isinstance(colspec, int) and colspec not in data_dict:
colspec = orig_names[colspec]
if _isindex(colspec):
Expand Down Expand Up @@ -1146,7 +1147,11 @@ def _try_convert_dates(parser: Callable, colspec, data_dict, columns):
else:
colnames.append(c)

new_name = "_".join([str(x) for x in colnames])
new_name: tuple | str
if all(isinstance(x, tuple) for x in colnames):
new_name = tuple(map("_".join, zip(*colnames)))
else:
new_name = "_".join([str(x) for x in colnames])
to_parse = [np.asarray(data_dict[c]) for c in colnames if c in data_dict]

new_col = parser(*to_parse)
Expand Down
33 changes: 33 additions & 0 deletions pandas/tests/io/parser/test_parse_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -1732,6 +1732,39 @@ def test_date_parser_and_names(all_parsers):
tm.assert_frame_equal(result, expected)


@skip_pyarrow
def test_date_parser_multiindex_columns(all_parsers):
parser = all_parsers
data = """a,b
1,2
2019-12-31,6"""
result = parser.read_csv(StringIO(data), parse_dates=[("a", "1")], header=[0, 1])
expected = DataFrame({("a", "1"): Timestamp("2019-12-31"), ("b", "2"): [6]})
tm.assert_frame_equal(result, expected)


@skip_pyarrow
@pytest.mark.parametrize(
"parse_spec, col_name",
[
([[("a", "1"), ("b", "2")]], ("a_b", "1_2")),
({("foo", "1"): [("a", "1"), ("b", "2")]}, ("foo", "1")),
],
)
def test_date_parser_multiindex_columns_combine_cols(all_parsers, parse_spec, col_name):
parser = all_parsers
data = """a,b,c
1,2,3
2019-12,-31,6"""
result = parser.read_csv(
StringIO(data),
parse_dates=parse_spec,
header=[0, 1],
)
expected = DataFrame({col_name: Timestamp("2019-12-31"), ("c", "3"): [6]})
tm.assert_frame_equal(result, expected)


@skip_pyarrow
def test_date_parser_usecols_thousands(all_parsers):
# GH#39365
Expand Down