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 5 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
)
44 changes: 44 additions & 0 deletions python/cudf/cudf/core/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -7709,6 +7709,50 @@ 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)

explode_num = self._column_names.index(column)
return super()._explode(
explode_num, None if ignore_index else self.index
)

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


Expand Down
23 changes: 22 additions & 1 deletion python/cudf/cudf/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,16 @@
import functools
import warnings
from collections import OrderedDict, abc as abc
from typing import TYPE_CHECKING, Any, Dict, Tuple, TypeVar, Union, overload
from typing import (
TYPE_CHECKING,
Any,
Dict,
Optional,
Tuple,
TypeVar,
Union,
overload,
)

import cupy
import numpy as np
Expand Down Expand Up @@ -573,6 +582,18 @@ def equals(self, other, **kwargs):
else:
return self._index.equals(other._index)

def _explode(self, explode_column_num: int, index: Optional[cudf.Index]):
isVoid marked this conversation as resolved.
Show resolved Hide resolved
if index is not None:
explode_column_num += index.nlevels
res_tbl = libcudf.lists.explode_outer(
cudf._lib.table.Table(self._data, index=index), explode_column_num
isVoid marked this conversation as resolved.
Show resolved Hide resolved
)

res = self.__class__._from_table(res_tbl)
if index is not None:
res.index.names = index.names
isVoid marked this conversation as resolved.
Show resolved Hide resolved
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(0, None if ignore_index else self.index)

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


Expand Down
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 @@ -8442,3 +8442,31 @@ def test_rename_for_level_is_None_MC():
got = gdf.rename(columns={"a": "f"}, level=None)

assert_eq(expect, got)


@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(ignore_index, p_index):
gdf = cudf.DataFrame(
{
"a": [[1, 2, 3], None, [4], [], [5, 6]],
"b": [11, 22, 33, 44, 55],
"c": ["a", "e", "i", "o", "u"],
},
index=p_index,
)
pdf = gdf.to_pandas(nullable=True)

expect = pdf.explode("a", ignore_index)
got = gdf.explode("a", ignore_index)

assert_eq(got, expect, check_dtype=False)
21 changes: 21 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,24 @@ def test_series_drop_raises():
actual = gs.drop("p", errors="ignore")

assert_eq(actual, expect)


@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(ignore_index, p_index):
gdf = cudf.Series([[1, 2, 3], None, [4], [], [5, 6]], index=p_index)
pdf = gdf.to_pandas(nullable=True)

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

assert_eq(expect, got, check_dtype=False)