Skip to content

BUG: concat losing columns dtypes for join=outer #47586

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 3 commits into from
Jul 3, 2022
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.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -995,6 +995,7 @@ Reshaping
- Bug in :func:`get_dummies` that selected object and categorical dtypes but not string (:issue:`44965`)
- Bug in :meth:`DataFrame.align` when aligning a :class:`MultiIndex` to a :class:`Series` with another :class:`MultiIndex` (:issue:`46001`)
- Bug in concatenation with ``IntegerDtype``, or ``FloatingDtype`` arrays where the resulting dtype did not mirror the behavior of the non-nullable dtypes (:issue:`46379`)
- Bug in :func:`concat` losing dtype of columns when ``join="outer"`` and ``sort=True`` (:issue:`47329`)
Copy link
Contributor

Choose a reason for hiding this comment

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

issue is marked as 1.4.4. ok to leave in 1.5 though (if so just change the issue and ignore this comment)

Copy link
Member Author

Choose a reason for hiding this comment

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

Changed the milestones.

initially we though this happens only
for ea dtypes, but this was wrong. Occurs also for numpy dtypes

- Bug in :func:`concat` not sorting the column names when ``None`` is included (:issue:`47331`)
- Bug in :func:`concat` with identical key leads to error when indexing :class:`MultiIndex` (:issue:`46519`)
- Bug in :meth:`DataFrame.join` with a list when using suffixes to join DataFrames with duplicate column names (:issue:`46396`)
Expand Down
34 changes: 30 additions & 4 deletions pandas/core/indexes/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
)
from pandas.errors import InvalidIndexError

from pandas.core.dtypes.cast import find_common_type
from pandas.core.dtypes.common import is_dtype_equal

from pandas.core.algorithms import safe_sort
Expand Down Expand Up @@ -223,7 +224,7 @@ def union_indexes(indexes, sort: bool | None = True) -> Index:

indexes, kind = _sanitize_and_check(indexes)

def _unique_indices(inds) -> Index:
def _unique_indices(inds, dtype) -> Index:
Copy link
Member

Choose a reason for hiding this comment

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

the docstring also needs updating at some point.

"""
Convert indexes to lists and concatenate them, removing duplicates.

Expand All @@ -243,7 +244,30 @@ def conv(i):
i = i.tolist()
return i

return Index(lib.fast_unique_multiple_list([conv(i) for i in inds], sort=sort))
return Index(
lib.fast_unique_multiple_list([conv(i) for i in inds], sort=sort),
dtype=dtype,
)

def _find_common_index_dtype(inds):
"""
Finds a common type for the indexes to pass through to resulting index.

Parameters
----------
inds: list of Index or list objects

Returns
-------
The common type or None if no indexes were given
"""
dtypes = [idx.dtype for idx in indexes if isinstance(idx, Index)]
if dtypes:
dtype = find_common_type(dtypes)
Copy link
Member

Choose a reason for hiding this comment

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

I assume we never pass a mixed list of Indexes and lists? could add type annotations here for clarity.

Copy link
Member Author

@phofl phofl Jul 6, 2022

Choose a reason for hiding this comment

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

A parent function uses list[list[Hashable] | Index], so not sure

Copy link
Member

Choose a reason for hiding this comment

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

I assumed that if we could pass a mixed list, then the logic added here would not account for the types in a list and only use the Indexes to find the common dtype. We could therefore expect this to raise in those cases?

Copy link
Member

@simonjayhawkins simonjayhawkins Jul 8, 2022

Choose a reason for hiding this comment

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

A parent function uses list[list[Hashable] | Index], so not sure

we may need to change to list[list[Hashable]] | list[Index]

else:
dtype = None

return dtype

if kind == "special":
result = indexes[0]
Expand Down Expand Up @@ -283,16 +307,18 @@ def conv(i):
return result

elif kind == "array":
dtype = _find_common_index_dtype(indexes)
index = indexes[0]
if not all(index.equals(other) for other in indexes[1:]):
index = _unique_indices(indexes)
index = _unique_indices(indexes, dtype)

name = get_unanimous_names(*indexes)[0]
if name != index.name:
index = index.rename(name)
return index
else: # kind='list'
return _unique_indices(indexes)
dtype = _find_common_index_dtype(indexes)
return _unique_indices(indexes, dtype)


def _sanitize_and_check(indexes):
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/reshape/concat/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,14 @@ def test_concat_range_index_result(self):
tm.assert_frame_equal(result, expected)
expected_index = pd.RangeIndex(0, 2)
tm.assert_index_equal(result.index, expected_index, exact=True)

@pytest.mark.parametrize("dtype", ["Int64", "object"])
def test_concat_index_keep_dtype(self, dtype):
# GH#47329
df1 = DataFrame([[0, 1, 1]], columns=Index([1, 2, 3], dtype=dtype))
df2 = DataFrame([[0, 1]], columns=Index([1, 2], dtype=dtype))
result = concat([df1, df2], ignore_index=True, join="outer", sort=True)
expected = DataFrame(
[[0, 1, 1.0], [0, 1, np.nan]], columns=Index([1, 2, 3], dtype=dtype)
)
tm.assert_frame_equal(result, expected)