Skip to content

PERF/REGR: revert #41785 #42338

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 4 commits into from
Jul 8, 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.3.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Pandas could not be built on PyPy (:issue:`42355`)
- :class:`DataFrame` constructed with with an older version of pandas could not be unpickled (:issue:`42345`)
- Performance regression in constructing a :class:`DataFrame` from a dictionary of dictionaries (:issue:`42338`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should have been 42248.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks, will add this to my next "collected cleanups" branch

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would need to backport, but no worries if added with other changes since the release readiness script will show that the release notes aren't in sync and I will sync directly to 1.3.x.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in #42516

-

.. ---------------------------------------------------------------------------
Expand Down
1 change: 1 addition & 0 deletions pandas/_libs/lib.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def is_string_array(values: np.ndarray, skipna: bool = False): ...
def is_float_array(values: np.ndarray, skipna: bool = False): ...
def is_integer_array(values: np.ndarray, skipna: bool = False): ...
def is_bool_array(values: np.ndarray, skipna: bool = False): ...
def fast_multiget(mapping: dict, keys: np.ndarray, default=np.nan) -> np.ndarray: ...
def fast_unique_multiple_list_gen(gen: Generator, sort: bool = True) -> list: ...
def fast_unique_multiple_list(lists: list, sort: bool = True) -> list: ...
def fast_unique_multiple(arrays: list, sort: bool = True) -> list: ...
Expand Down
22 changes: 22 additions & 0 deletions pandas/_libs/lib.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2955,6 +2955,28 @@ def to_object_array_tuples(rows: object) -> np.ndarray:
return result


@cython.wraparound(False)
@cython.boundscheck(False)
def fast_multiget(dict mapping, ndarray keys, default=np.nan) -> np.ndarray:
cdef:
Py_ssize_t i, n = len(keys)
object val
ndarray[object] output = np.empty(n, dtype='O')

if n == 0:
# kludge, for Series
return np.empty(0, dtype='f8')

for i in range(n):
val = keys[i]
if val in mapping:
output[i] = mapping[val]
else:
output[i] = default

return maybe_convert_objects(output)


def is_bool_list(obj: list) -> bool:
"""
Check if this list contains only bool or np.bool_ objects.
Expand Down
15 changes: 15 additions & 0 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,21 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> tuple[DtypeObj,
return dtype, val


def dict_compat(d: dict[Scalar, Scalar]) -> dict[Scalar, Scalar]:
"""
Convert datetimelike-keyed dicts to a Timestamp-keyed dict.

Parameters
----------
d: dict-like object

Returns
-------
dict
"""
return {maybe_box_datetimelike(key): value for key, value in d.items()}


def infer_dtype_from_array(
arr, pandas_dtype: bool = False
) -> tuple[DtypeObj, ArrayLike]:
Expand Down
20 changes: 16 additions & 4 deletions pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar,
dict_compat,
maybe_cast_to_datetime,
maybe_convert_platform,
maybe_infer_to_datetimelike,
Expand Down Expand Up @@ -59,15 +60,16 @@
TimedeltaArray,
)
from pandas.core.construction import (
create_series_with_explicit_dtype,
ensure_wrapped_if_datetimelike,
extract_array,
range_to_ndarray,
sanitize_array,
)
from pandas.core.indexes import base as ibase
from pandas.core.indexes.api import (
DatetimeIndex,
Index,
TimedeltaIndex,
ensure_index,
get_objs_combined_axis,
union_indexes,
Expand Down Expand Up @@ -556,6 +558,7 @@ def convert(v):


def _homogenize(data, index: Index, dtype: DtypeObj | None) -> list[ArrayLike]:
oindex = None
homogenized = []

for val in data:
Expand All @@ -570,9 +573,18 @@ def _homogenize(data, index: Index, dtype: DtypeObj | None) -> list[ArrayLike]:
val = val._values
else:
if isinstance(val, dict):
# see test_constructor_subclass_dict
# test_constructor_dict_datetime64_index
val = create_series_with_explicit_dtype(val, index=index)._values
# GH#41785 this _should_ be equivalent to (but faster than)
# val = create_series_with_explicit_dtype(val, index=index)._values
if oindex is None:
oindex = index.astype("O")

if isinstance(index, (DatetimeIndex, TimedeltaIndex)):
# see test_constructor_dict_datetime64_index
val = dict_compat(val)
else:
# see test_constructor_subclass_dict
val = dict(val)
val = lib.fast_multiget(val, oindex._values, default=np.nan)

val = sanitize_array(
val, index, dtype=dtype, copy=False, raise_cast_failure=False
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/dtypes/cast/test_dict_compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import numpy as np

from pandas.core.dtypes.cast import dict_compat

from pandas import Timestamp


def test_dict_compat():
data_datetime64 = {np.datetime64("1990-03-15"): 1, np.datetime64("2015-03-15"): 2}
data_unchanged = {1: 2, 3: 4, 5: 6}
expected = {Timestamp("1990-3-15"): 1, Timestamp("2015-03-15"): 2}
assert dict_compat(data_datetime64) == expected
assert dict_compat(expected) == expected
assert dict_compat(data_unchanged) == data_unchanged