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

Adds explode API #7607

Merged
merged 17 commits into from
Mar 18, 2021
Merged
Show file tree
Hide file tree
Changes from 10 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
13 changes: 13 additions & 0 deletions python/cudf/cudf/_lib/cpp/lists/explode.pxd
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Copyright (c) 2021, NVIDIA CORPORATION.

from libcpp.memory cimport unique_ptr

from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport size_type

cdef extern from "cudf/lists/explode.hpp" namespace "cudf" nogil:
cdef unique_ptr[table] explode_outer(
const table_view,
size_type explode_column_idx,
) except +
25 changes: 24 additions & 1 deletion python/cudf/cudf/_lib/lists.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ from libcpp.utility cimport move
from cudf._lib.cpp.lists.count_elements cimport (
count_elements as cpp_count_elements
)
from cudf._lib.cpp.lists.explode cimport (
explode_outer as cpp_explode_outer
)
from cudf._lib.cpp.lists.lists_column_view cimport lists_column_view
from cudf._lib.cpp.column.column_view cimport column_view
from cudf._lib.cpp.column.column cimport column

from cudf._lib.column cimport Column
from cudf._lib.cpp.table.table cimport table
from cudf._lib.cpp.table.table_view cimport table_view
from cudf._lib.cpp.types cimport size_type

from cudf._lib.column cimport Column
from cudf._lib.table cimport Table

from cudf.core.dtypes import ListDtype

Expand All @@ -32,3 +39,19 @@ def count_elements(Column col):

result = Column.from_unique_ptr(move(c_result))
return result


def explode_outer(Table tbl, int explode_column_idx):
cdef table_view c_table_view = tbl.view()
cdef size_type c_explode_column_idx = explode_column_idx

cdef unique_ptr[table] c_result

with nogil:
c_result = move(cpp_explode_outer(c_table_view, c_explode_column_idx))

return Table.from_unique_ptr(
move(c_result),
column_names=tbl._column_names,
index_names=tbl._index_names
)
41 changes: 41 additions & 0 deletions python/cudf/cudf/core/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -7709,6 +7709,47 @@ def equals(self, other):
return False
return super().equals(other)

def explode(self, column, ignore_index=False):
"""
Transform each element of a list-like to a row, replicating index
values.

Parameters
----------
column : str or tuple
Column to explode.
ignore_index : bool, default False
If True, the resulting index will be labeled 0, 1, …, n - 1.

Returns
-------
DataFrame

Examples
-------
isVoid marked this conversation as resolved.
Show resolved Hide resolved
>>> import cudf
>>> cudf.DataFrame(
{"a": [[1, 2, 3], [], None, [4, 5]], "b": [11, 22, 33, 44]})
a b
0 [1, 2, 3] 11
1 [] 22
2 None 33
3 [4, 5] 44
>>> df.explode('a')
a b
0 1 11
0 2 11
0 3 11
1 <NA> 22
2 <NA> 33
3 4 44
3 5 44
"""
if column not in self._column_names:
raise KeyError(column)

return super()._explode(column, ignore_index)

_accessors = set() # type: Set[Any]


Expand Down
32 changes: 32 additions & 0 deletions python/cudf/cudf/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from cudf.utils.dtypes import (
is_categorical_dtype,
is_column_like,
is_list_dtype,
is_numerical_dtype,
is_scalar,
min_scalar_type,
Expand Down Expand Up @@ -573,6 +574,37 @@ def equals(self, other, **kwargs):
else:
return self._index.equals(other._index)

def _explode(self, explode_column: Any, ignore_index: bool):
"""Helper function for `explode` in Series and Dataframe.
if the designated column to explode is non-nested, a copy
of the frame is returned. Otherwise, if ignore_index is
isVoid marked this conversation as resolved.
Show resolved Hide resolved
set, the original index is not exploded and will use
a `RangeIndex` instead.
"""
if not is_list_dtype(self._data[explode_column].dtype):
copy = self.copy()
if ignore_index:
copy._index = cudf.RangeIndex(copy._num_rows)
isVoid marked this conversation as resolved.
Show resolved Hide resolved
return copy

explode_column_num = self._column_names.index(explode_column)
if ignore_index:
tmp_index, self._index = self._index, None
isVoid marked this conversation as resolved.
Show resolved Hide resolved
elif self._index is not None:
explode_column_num += self._index.nlevels

res_tbl = libcudf.lists.explode_outer(self, explode_column_num)
res = self.__class__._from_table(res_tbl)

res._data.multiindex = self._data.multiindex
res._data._level_names = self._data._level_names
Comment on lines +591 to +592
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do we not have a helper function that handles all of the "gotchas" in this?

Copy link
Contributor Author

@isVoid isVoid Mar 18, 2021

Choose a reason for hiding this comment

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

Checked with @shwina, and can't think of any.. ._data is constructed inside from_unique_ptr, which has no information about multiindex and _level_names.

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree it's not ideal. One alternative I've considered in the past is a custom ColumnMeta type containing information about column names:

class ColumnMeta:
    names: Tuple[Any]
    multiindex: bool
    level_names: Tuple[Any]

And we pass objects of that type as arguments to ._from_unique_ptr:

cdef from_unique_ptr(unique_ptr[table] c_tbl, ColumnMeta data_meta, ColumnMeta index_meta=None):
    pass

Maybe a bit out of scope for this PR though.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Definitely out of scope for this PR, but I like it a lot.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Is ColumnMeta owned and maintained by some class? Or is it a message interface that gets created on the fly and passes around classes?

Copy link
Contributor

Choose a reason for hiding this comment

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

Good question -- I think we should have a separate discussion about this outside the context of this PR. Happy to sync offline and then raise an issue?


if ignore_index:
self._index = tmp_index
elif self._index is not None:
res.index.names = self._index.names
return res

def _get_columns_by_label(self, labels, downcast):
"""
Returns columns of the Frame specified by `labels`
Expand Down
37 changes: 37 additions & 0 deletions python/cudf/cudf/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -6364,6 +6364,43 @@ def keys(self):
"""
return self.index

def explode(self, ignore_index=False):
"""
Transform each element of a list-like to a row, replicating index
values.

Parameters
----------
ignore_index : bool, default False
If True, the resulting index will be labeled 0, 1, …, n - 1.

Returns
-------
DataFrame

Examples
-------
isVoid marked this conversation as resolved.
Show resolved Hide resolved
>>> import cudf
>>> s = cudf.Series([[1, 2, 3], [], None, [4, 5]])
>>> s
0 [1, 2, 3]
1 []
2 None
3 [4, 5]
dtype: list
>>> s.explode()
0 1
0 2
0 3
1 <NA>
2 <NA>
3 4
3 5
dtype: int64
"""

return super()._explode(self._column_names[0], ignore_index)

_accessors = set() # type: Set[Any]


Expand Down
53 changes: 53 additions & 0 deletions python/cudf/cudf/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -8442,3 +8442,56 @@ def test_rename_for_level_is_None_MC():
got = gdf.rename(columns={"a": "f"}, level=None)

assert_eq(expect, got)


@pytest.mark.parametrize(
"data",
[
[
[[1, 2, 3], 11, "a"],
[None, 22, "e"],
[[4], 33, "i"],
[[], 44, "o"],
[[5, 6], 55, "u"],
], # nested
[
[1, 11, "a"],
[2, 22, "e"],
[3, 33, "i"],
[4, 44, "o"],
[5, 55, "u"],
], # non-nested
],
)
@pytest.mark.parametrize(
("labels", "label_to_explode"),
[
(None, 0),
(pd.Index(["a", "b", "c"]), "a"),
(
pd.MultiIndex.from_tuples(
[(0, "a"), (0, "b"), (1, "a")], names=["l0", "l1"]
),
(0, "a"),
),
],
)
@pytest.mark.parametrize("ignore_index", [True, False])
@pytest.mark.parametrize(
"p_index",
[
None,
["ia", "ib", "ic", "id", "ie"],
pd.MultiIndex.from_tuples(
[(0, "a"), (0, "b"), (0, "c"), (1, "a"), (1, "b")]
),
],
)
def test_explode(data, labels, ignore_index, p_index, label_to_explode):
pdf = pd.DataFrame(data, index=p_index, columns=labels)
gdf = cudf.from_pandas(pdf)

expect = pdf.explode(label_to_explode, ignore_index)
got = gdf.explode(label_to_explode, ignore_index)

assert_eq(expect, got, check_dtype=False)
30 changes: 30 additions & 0 deletions python/cudf/cudf/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1118,3 +1118,33 @@ def test_series_drop_raises():
actual = gs.drop("p", errors="ignore")

assert_eq(actual, expect)


@pytest.mark.parametrize(
"data",
[[[1, 2, 3], None, [4], [], [5, 6]], [1, 2, 3, 4, 5]], # non-nested
)
@pytest.mark.parametrize("ignore_index", [True, False])
@pytest.mark.parametrize(
"p_index",
[
None,
["ia", "ib", "ic", "id", "ie"],
pd.MultiIndex.from_tuples(
[(0, "a"), (0, "b"), (0, "c"), (1, "a"), (1, "b")]
),
],
)
def test_explode(data, ignore_index, p_index):
pdf = pd.Series(data, index=p_index, name="someseries")
gdf = cudf.from_pandas(pdf)

expect = pdf.explode(ignore_index)
got = gdf.explode(ignore_index)

if data == [1, 2, 3, 4, 5] and ignore_index and p_index is not None:
# https://github.com/pandas-dev/pandas/issues/40487
with pytest.raises(AssertionError, match="different"):
assert_eq(expect, got, check_dtype=False)
else:
assert_eq(expect, got, check_dtype=False)