Skip to content

Commit

Permalink
Fix StructColumn.to_pandas type handling issues (#9388)
Browse files Browse the repository at this point in the history
Fixes: #9383 

This PR preserves `datetime` & `timedelta` types in `StructColumn` upon conversion to `pd.Series`, and also preserves `int`   values to be `int` rather than converting to `float`.

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

Approvers:
  - Michael Wang (https://github.com/isVoid)

URL: #9388
  • Loading branch information
galipremsagar authored Oct 6, 2021
1 parent a743ce8 commit 4e7c820
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
11 changes: 11 additions & 0 deletions python/cudf/cudf/core/column/struct.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Copyright (c) 2020, NVIDIA CORPORATION.
from __future__ import annotations

import pandas as pd
import pyarrow as pa

import cudf
Expand Down Expand Up @@ -80,6 +81,16 @@ def to_arrow(self):
pa_type, len(self), buffers, children=children
)

def to_pandas(self, index: pd.Index = None, **kwargs) -> "pd.Series":
# We cannot go via Arrow's `to_pandas` because of the following issue:
# https://issues.apache.org/jira/browse/ARROW-12680

pd_series = pd.Series(self.to_arrow().tolist(), dtype="object")

if index is not None:
pd_series.index = index
return pd_series

def __getitem__(self, args):
result = super().__getitem__(args)
if isinstance(result, dict):
Expand Down
34 changes: 33 additions & 1 deletion python/cudf/cudf/tests/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import cudf
from cudf.core.dtypes import StructDtype
from cudf.testing._utils import assert_eq
from cudf.testing._utils import DATETIME_TYPES, TIMEDELTA_TYPES, assert_eq


@pytest.mark.parametrize(
Expand Down Expand Up @@ -292,3 +292,35 @@ def test_struct_field_errors(data):

with pytest.raises(IndexError):
got.struct.field(100)


@pytest.mark.parametrize("dtype", DATETIME_TYPES + TIMEDELTA_TYPES)
def test_struct_with_datetime_and_timedelta(dtype):
df = cudf.DataFrame(
{
"a": [12, 232, 2334],
"datetime": cudf.Series([23432, 3432423, 324324], dtype=dtype),
}
)
series = df.to_struct()
a_array = np.array([12, 232, 2334])
datetime_array = np.array([23432, 3432423, 324324]).astype(dtype)

actual = series.to_pandas()
values_list = []
for i, val in enumerate(a_array):
values_list.append({"a": val, "datetime": datetime_array[i]})

expected = pd.Series(values_list)
assert_eq(expected, actual)


def test_struct_int_values():
series = cudf.Series(
[{"a": 1, "b": 2}, {"a": 10, "b": None}, {"a": 5, "b": 6}]
)
actual_series = series.to_pandas()

assert isinstance(actual_series[0]["b"], int)
assert isinstance(actual_series[1]["b"], type(None))
assert isinstance(actual_series[2]["b"], int)

0 comments on commit 4e7c820

Please sign in to comment.