Skip to content

REF/INT: preserve block type in joining when only having a single block #17954

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
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
10 changes: 9 additions & 1 deletion pandas/core/internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -5182,7 +5182,15 @@ def concatenate_block_managers(mgrs_indexers, axes, concat_axis, copy):

for placement, join_units in concat_plan:

if is_uniform_join_units(join_units):
if len(join_units) == 1 and not join_units[0].indexers:
b = join_units[0].block
values = b.values
if copy:
values = values.copy()
elif not copy:
values = values.view()
b = b.make_block_same_class(values, placement=placement)
elif is_uniform_join_units(join_units):
b = join_units[0].block.concat_same_type(
[ju.block for ju in join_units], placement=placement)
else:
Expand Down
29 changes: 21 additions & 8 deletions pandas/tests/internals/test_external_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from pandas.core.internals import (
Block, BlockManager, SingleBlockManager, NonConsolidatableMixIn)

import pytest


class CustomBlock(NonConsolidatableMixIn, Block):

Expand All @@ -25,6 +27,17 @@ def concat_same_type(self, to_concat, placement=None):
values, placement=placement or slice(0, len(values), 1))


@pytest.fixture
def df():
df1 = pd.DataFrame({'a': [1, 2, 3]})
blocks = df1._data.blocks
values = np.arange(3, dtype='int64')
custom_block = CustomBlock(values, placement=slice(1, 2))
blocks = blocks + (custom_block,)
block_manager = BlockManager(blocks, [pd.Index(['a', 'b']), df1.index])
return pd.DataFrame(block_manager)


def test_custom_repr():
values = np.arange(3, dtype='int64')

Expand All @@ -51,14 +64,14 @@ def test_concat_series():
assert isinstance(res._data.blocks[0], CustomBlock)


def test_concat_dataframe():
def test_concat_dataframe(df):
# GH17728
df = pd.DataFrame({'a': [1, 2, 3]})
blocks = df._data.blocks
values = np.arange(3, dtype='int64')
custom_block = CustomBlock(values, placement=slice(1, 2))
blocks = blocks + (custom_block, )
block_manager = BlockManager(blocks, [pd.Index(['a', 'b']), df.index])
df = pd.DataFrame(block_manager)
res = pd.concat([df, df])
assert isinstance(res._data.blocks[1], CustomBlock)


def test_concat_axis1(df):
# GH17954
df2 = pd.DataFrame({'c': [.1, .2, .3]})
res = pd.concat([df, df2], axis=1)
assert isinstance(res._data.blocks[1], CustomBlock)