Skip to content

Commit

Permalink
feat(api): add name kwarg to Table.value_counts() (#10361)
Browse files Browse the repository at this point in the history
Co-authored-by: Phillip Cloud <[email protected]>
  • Loading branch information
NickCrews and cpcloud authored Oct 26, 2024
1 parent 41a9b7d commit 12e6057
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions ibis/expr/types/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -4566,9 +4566,15 @@ def window_by(

return WindowedTable(self, time_col)

def value_counts(self) -> ir.Table:
def value_counts(self, *, name: str | None = None) -> ir.Table:
"""Compute a frequency table of this table's values.
Parameters
----------
name
The name to use for the frequency column. A suitable name will be
automatically generated if not provided.
Returns
-------
Table
Expand All @@ -4591,16 +4597,16 @@ def value_counts(self) -> ir.Table:
│ Adelie │ Torgersen │ NULL │ NULL │ NULL │ … │
│ Adelie │ Torgersen │ 36.7 │ 19.3 │ 193 │ … │
└─────────┴───────────┴────────────────┴───────────────┴───────────────────┴───┘
>>> t.year.value_counts().order_by("year")
┏━━━━━━━┳━━━━━━━━━━━━
┃ year ┃ year_count
┡━━━━━━━╇━━━━━━━━━━━━
│ int64 │ int64
├───────┼────────────
│ 2007 │ 110 │
│ 2008 │ 114 │
│ 2009 │ 120 │
└───────┴────────────
>>> t.year.value_counts(name="n").order_by("year")
┏━━━━━━━┳━━━━━━━┓
┃ year ┃ n
┡━━━━━━━╇━━━━━━━┩
│ int64 │ int64 │
├───────┼───────┤
│ 2007 │ 110 │
│ 2008 │ 114 │
│ 2009 │ 120 │
└───────┴───────┘
>>> t[["year", "island"]].value_counts().order_by("year", "island")
┏━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
┃ year ┃ island ┃ year_island_count ┃
Expand All @@ -4619,9 +4625,9 @@ def value_counts(self) -> ir.Table:
└───────┴───────────┴───────────────────┘
"""
columns = self.columns
return self.group_by(columns).agg(
lambda t: t.count().name("_".join(columns) + "_count")
)
if name is None:
name = "_".join(columns) + "_count"
return self.group_by(columns).agg(lambda t: t.count().name(name))

def unnest(
self, column, offset: str | None = None, keep_empty: bool = False
Expand Down

0 comments on commit 12e6057

Please sign in to comment.