Skip to content

Commit

Permalink
Return same type as the original index for .loc operations (#15717)
Browse files Browse the repository at this point in the history
Fixes: #15716 

This PR makes changes to `.loc` by preserving the original type at the end of the operation.

Authors:
  - GALI PREM SAGAR (https://github.com/galipremsagar)

Approvers:
  - Matthew Roeschke (https://github.com/mroeschke)

URL: #15717
  • Loading branch information
galipremsagar authored May 12, 2024
1 parent ce1933f commit 425a5da
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
5 changes: 5 additions & 0 deletions python/cudf/cudf/core/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,11 @@ def _getitem_tuple_arg(self, arg):
# as join is not assigning any names to index,
# update it over here
df.index.name = columns_df.index.name
if not isinstance(
df.index, MultiIndex
) and is_numeric_dtype(df.index.dtype):
# Preserve the original index type.
df.index = df.index.astype(self._frame.index.dtype)
df = df.sort_values(by=[tmp_col_name, cantor_name])
df.drop(columns=[tmp_col_name, cantor_name], inplace=True)
# There were no indices found
Expand Down
18 changes: 18 additions & 0 deletions python/cudf/cudf/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -11010,3 +11010,21 @@ def test_dataframe_init_with_nans():
assert gdf["a"].dtype == np.dtype("float64")
pdf = pd.DataFrame({"a": [1, 2, 3, np.nan]})
assert_eq(pdf, gdf)


@pytest.mark.parametrize("dtype1", ["int16", "float32"])
@pytest.mark.parametrize("dtype2", ["int16", "float32"])
def test_dataframe_loc_int_float(dtype1, dtype2):
df = cudf.DataFrame(
{"a": [10, 11, 12, 13, 14]},
index=cudf.Index([1, 2, 3, 4, 5], dtype=dtype1),
)
pdf = df.to_pandas()

gidx = cudf.Index([2, 3, 4], dtype=dtype2)
pidx = gidx.to_pandas()

actual = df.loc[gidx]
expected = pdf.loc[pidx]

assert_eq(actual, expected, check_index_type=True, check_dtype=True)

0 comments on commit 425a5da

Please sign in to comment.