Skip to content

PERF: _form_blocks #43144

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 5 commits into from
Aug 23, 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
100 changes: 47 additions & 53 deletions pandas/core/internals/managers.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
from __future__ import annotations

from collections import defaultdict
import itertools
from typing import (
Any,
Callable,
DefaultDict,
Hashable,
Sequence,
TypeVar,
Expand Down Expand Up @@ -67,9 +65,7 @@
)
from pandas.core.internals.blocks import (
Block,
CategoricalBlock,
DatetimeTZBlock,
ExtensionBlock,
ensure_block_shape,
extend_blocks,
get_block_type,
Expand Down Expand Up @@ -1863,63 +1859,56 @@ def construction_error(
# -----------------------------------------------------------------------


def _form_blocks(arrays: list[ArrayLike], consolidate: bool) -> list[Block]:

items_dict: DefaultDict[str, list] = defaultdict(list)

for i, name_idx in enumerate(range(len(arrays))):
def _grouping_func(tup):
Copy link
Contributor

Choose a reason for hiding this comment

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

if u can type in a follow on

# compat for numpy<1.21, in which comparing a np.dtype with an ExtensionDtype
# raises instead of returning False. Once earlier numpy versions are dropped,
# this can be simplified to `return tup[1].dtype`
dtype = tup[1].dtype
return isinstance(dtype, np.dtype), dtype

v = arrays[name_idx]

block_type = get_block_type(v)
items_dict[block_type.__name__].append((i, v))
def _form_blocks(arrays: list[ArrayLike], consolidate: bool) -> list[Block]:
tuples = list(enumerate(arrays))

blocks: list[Block] = []
if len(items_dict["NumericBlock"]):
numeric_blocks = multi_blockify(
items_dict["NumericBlock"], consolidate=consolidate
)
blocks.extend(numeric_blocks)
if not consolidate:
nbs = _tuples_to_blocks_no_consolidate(tuples, dtype=None)
return nbs

if len(items_dict["DatetimeLikeBlock"]):
dtlike_blocks = multi_blockify(
items_dict["DatetimeLikeBlock"], consolidate=consolidate
)
blocks.extend(dtlike_blocks)
# group by dtype
grouper = itertools.groupby(tuples, _grouping_func)

if len(items_dict["DatetimeTZBlock"]):
dttz_blocks = [
DatetimeTZBlock(
ensure_block_shape(extract_array(array), 2),
placement=BlockPlacement(i),
ndim=2,
)
for i, array in items_dict["DatetimeTZBlock"]
]
blocks.extend(dttz_blocks)
nbs = []
for (_, dtype), tup_block in grouper:
block_type = get_block_type(None, dtype)

if len(items_dict["ObjectBlock"]) > 0:
object_blocks = simple_blockify(
items_dict["ObjectBlock"], np.object_, consolidate=consolidate
)
blocks.extend(object_blocks)
if isinstance(dtype, np.dtype):
is_dtlike = dtype.kind in ["m", "M"]

if len(items_dict["CategoricalBlock"]) > 0:
cat_blocks = [
CategoricalBlock(array, placement=BlockPlacement(i), ndim=2)
for i, array in items_dict["CategoricalBlock"]
]
blocks.extend(cat_blocks)
if issubclass(dtype.type, (str, bytes)):
dtype = np.dtype(object)

if len(items_dict["ExtensionBlock"]):
external_blocks = [
ExtensionBlock(array, placement=BlockPlacement(i), ndim=2)
for i, array in items_dict["ExtensionBlock"]
]
values, placement = _stack_arrays(list(tup_block), dtype)
if is_dtlike:
values = ensure_wrapped_if_datetimelike(values)
blk = block_type(values, placement=BlockPlacement(placement), ndim=2)
nbs.append(blk)

blocks.extend(external_blocks)
elif is_1d_only_ea_dtype(dtype):
dtype_blocks = [
block_type(x[1], placement=BlockPlacement(x[0]), ndim=2)
for x in tup_block
]
nbs.extend(dtype_blocks)

return blocks
else:
dtype_blocks = [
block_type(
ensure_block_shape(x[1], 2), placement=BlockPlacement(x[0]), ndim=2
)
for x in tup_block
]
nbs.extend(dtype_blocks)
return nbs


def simple_blockify(tuples, dtype, consolidate: bool) -> list[Block]:
Expand Down Expand Up @@ -1970,11 +1959,16 @@ def _tuples_to_blocks_no_consolidate(tuples, dtype: DtypeObj | None) -> list[Blo
if dtype is not None:
return [
new_block(
np.atleast_2d(x[1].astype(dtype, copy=False)), placement=x[0], ndim=2
ensure_block_shape(x[1].astype(dtype, copy=False), ndim=2),
placement=x[0],
ndim=2,
)
for x in tuples
]
return [new_block(np.atleast_2d(x[1]), placement=x[0], ndim=2) for x in tuples]
return [
new_block(ensure_block_shape(x[1], ndim=2), placement=x[0], ndim=2)
for x in tuples
]


def _stack_arrays(tuples, dtype: np.dtype):
Expand Down
5 changes: 3 additions & 2 deletions pandas/tests/io/pytables/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,9 @@ def test_categorical(setup_path):
# Make sure the metadata is OK
info = store.info()
assert "/df2 " in info
# assert '/df2/meta/values_block_0/meta' in info
assert "/df2/meta/values_block_1/meta" in info
# df2._mgr.blocks[0] and df2._mgr.blocks[2] are Categorical
assert "/df2/meta/values_block_0/meta" in info
assert "/df2/meta/values_block_2/meta" in info

# unordered
_maybe_remove(store, "s2")
Expand Down