Skip to content

Commit

Permalink
Add Dataframe and Index nunique
Browse files Browse the repository at this point in the history
  • Loading branch information
martinfalisse committed Jan 27, 2022
1 parent 8fd7dd2 commit 7291d3a
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 1 deletion.
31 changes: 31 additions & 0 deletions python/cudf/cudf/core/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -6145,6 +6145,37 @@ def __dataframe__(
self, nan_as_null=nan_as_null, allow_copy=allow_copy
)

def nunique(self, axis=0, dropna=True):
"""
Count number of distinct elements in specified axis.
Return Series with number of distinct elements. Can ignore NaN values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
dropna : bool, default True
Don't include NaN in the counts.
Returns
-------
Series
Examples
--------
>>> import cudf
>>> df = cudf.DataFrame({'A': [4, 5, 6], 'B': [4, 1, 1]})
>>> df.nunique()
A 3
B 2
dtype: int64
"""
if axis != 0:
raise NotImplementedError(
"axis parameter is not supported yet."
)

return cudf.Series(super().nunique(method="sort", dropna=dropna))

def from_dataframe(df, allow_copy=False):
return df_protocol.from_dataframe(df, allow_copy=allow_copy)
Expand Down
21 changes: 21 additions & 0 deletions python/cudf/cudf/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6420,6 +6420,27 @@ def ge(self, other, axis="columns", level=None, fill_value=None):
other=other, fn="ge", fill_value=fill_value, can_reindex=True
)

def nunique(self, method: builtins.str = "sort", dropna: bool = True):
"""
Returns a per column mapping with counts of unique values for
each column.
Parameters
----------
method : builtins.str, default "sort"
Method used by cpp_distinct_count
dropna : bool, default True
Don't include NaN in the counts.
Returns
-------
dict
Name and unique value counts of each column in frame.
"""
return {
name: col.distinct_count(method=method, dropna=dropna)
for name, col in self._data.items()
}

def _get_replacement_values_for_columns(
to_replace: Any, value: Any, columns_dtype_map: Dict[Any, Any]
Expand Down
2 changes: 1 addition & 1 deletion python/cudf/cudf/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -2947,7 +2947,7 @@ def nunique(self, method="sort", dropna=True):
raise NotImplementedError(msg)
if self.null_count == len(self):
return 0
return self._column.distinct_count(method, dropna)
return super().nunique(method, dropna)

def value_counts(
self,
Expand Down
18 changes: 18 additions & 0 deletions python/cudf/cudf/core/single_column_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,3 +336,21 @@ def _make_operands_for_binop(
return NotImplemented

return {result_name: (self._column, other, reflect, fill_value)}

def nunique(self, method: builtins.str = "sort", dropna: bool = True):
"""
Returns count of unique values for the column.
Parameters
----------
method : builtins.str, default "sort"
Method used by cpp_distinct_count
dropna : bool, default True
Don't include NaN in the counts.
Returns
-------
int
Number of unique values in the column.
"""
return sum(super().nunique(method=method, dropna=dropna).values())
24 changes: 24 additions & 0 deletions python/cudf/cudf/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -9077,3 +9077,27 @@ def test_dataframe_assign_cp_np_array():
gdf[[f"f_{i}" for i in range(n)]] = cp_ndarray

assert_eq(pdf, gdf)

@pytest.mark.parametrize(
"data", [{"a": [1, 2, 3], "b": [1, 1, 0]}],
)
def test_dataframe_nunique(data):
gdf = cudf.DataFrame(data)
pdf = gdf.to_pandas()

actual = gdf.nunique()
expected = pdf.nunique()

assert_eq(expected, actual)

@pytest.mark.parametrize(
"data", [{ "key": [0, 1, 1, 0, 0, 1], "val": [1, 8, 3, 9, -3, 8]}],
)
def test_dataframe_nunique_index(data):
gdf = cudf.DataFrame(data)
pdf = gdf.to_pandas()

actual = gdf.index.nunique()
expected = pdf.index.nunique()

assert_eq(expected, actual)
24 changes: 24 additions & 0 deletions python/cudf/cudf/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1517,3 +1517,27 @@ def test_series_transpose(data):
assert_eq(pd_transposed, cudf_transposed)
assert_eq(pd_property, cudf_property)
assert_eq(cudf_transposed, csr)

@pytest.mark.parametrize(
"data", [1, 3, 5, 7, 7],
)
def test_series_nunique(data):
cd_s = cudf.Series(data)
pd_s = cd_s.to_pandas()

actual = cd_s.nunique()
expected = pd_s.nunique()

assert_eq(expected, actual)

@pytest.mark.parametrize(
"data", [1, 3, 5, 7, 7],
)
def test_series_nunique_index(data):
cd_s = cudf.Series(data)
pd_s = cd_s.to_pandas()

actual = cd_s.index.nunique()
expected = pd_s.index.nunique()

assert_eq(expected, actual)

0 comments on commit 7291d3a

Please sign in to comment.