Skip to content
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

Preserve index name in reindex #13917

Merged
merged 2 commits into from
Aug 18, 2023
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
27 changes: 25 additions & 2 deletions python/cudf/cudf/core/indexed_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2582,10 +2582,12 @@ def _reindex(

df = self
if index is not None:
index = cudf.core.index.as_index(index)
index = cudf.core.index.as_index(
index, name=getattr(index, "name", self._index.name)
)

idx_dtype_match = (df.index.nlevels == index.nlevels) and all(
left_dtype == right_dtype
_is_same_dtype(left_dtype, right_dtype)
for left_dtype, right_dtype in zip(
(col.dtype for col in df.index._data.columns),
(col.dtype for col in index._data.columns),
Expand Down Expand Up @@ -5405,3 +5407,24 @@ def _drop_rows_by_labels(
res = obj.to_frame(name="tmp").join(key_df, how="leftanti")["tmp"]
res.name = obj.name
return res


def _is_same_dtype(lhs_dtype, rhs_dtype):
# Utility specific to `_reindex` to check
# for matching column dtype.
if lhs_dtype == rhs_dtype:
return True
elif (
is_categorical_dtype(lhs_dtype)
and not is_categorical_dtype(rhs_dtype)
and lhs_dtype.categories.dtype == rhs_dtype
):
return True
elif (
is_categorical_dtype(rhs_dtype)
and not is_categorical_dtype(lhs_dtype)
and rhs_dtype.categories.dtype == lhs_dtype
):
return True
else:
return False
28 changes: 28 additions & 0 deletions python/cudf/cudf/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -10288,3 +10288,31 @@ def test_dataframe_mixed_dtype_error(dtype):
pdf = pd.Series([1, 2, 3], dtype=dtype).to_frame().astype(object)
with pytest.raises(TypeError):
cudf.from_pandas(pdf)


@pytest.mark.parametrize(
"index_data,name",
[([10, 13], "a"), ([30, 40, 20], "b"), (["ef"], "c"), ([2, 3], "Z")],
)
def test_dataframe_reindex_with_index_names(index_data, name):
gdf = cudf.DataFrame(
{
"a": [10, 12, 13],
"b": [20, 30, 40],
"c": cudf.Series(["ab", "cd", "ef"], dtype="category"),
}
)
if name in gdf.columns:
gdf = gdf.set_index(name)
pdf = gdf.to_pandas()

gidx = cudf.Index(index_data, name=name)
actual = gdf.reindex(gidx)
expected = pdf.reindex(gidx.to_pandas())

assert_eq(actual, expected)

actual = gdf.reindex(index_data)
expected = pdf.reindex(index_data)

assert_eq(actual, expected)