Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
c2009ed
docs: link to ML.EVALUATE BQML page for score() methods
ashleyxuu Oct 24, 2023
09ad5e4
feat: label query job with bigframes-api-xx using decorator
ashleyxuu Oct 25, 2023
4f4eb9b
reorganize the commit
ashleyxuu Oct 25, 2023
9ee937c
Merge branch 'main' into ashleyxu-add-api-methods
ashleyxuu Oct 26, 2023
272f0af
test: Log slowest tests durations (#146)
shobsi Oct 26, 2023
0e4c49c
docs: link to ML.EVALUATE BQML page for score() methods (#137)
ashleyxuu Oct 26, 2023
aad2c1a
feat: populate ibis version in user agent (#140)
ashleyxuu Oct 26, 2023
1043d6d
fix: don't override the global logging config (#138)
tswast Oct 26, 2023
1f49ef9
fix: use indexee's session for loc listlike cases (#152)
milkshakeiii Oct 26, 2023
c4c1e6e
feat: add pandas.qcut (#104)
TrevorBergeron Oct 26, 2023
4a27f44
feat: add unstack to series, add level param (#115)
TrevorBergeron Oct 26, 2023
fface57
feat: add `DataFrame.to_pandas_batches()` to download large `DataFram…
tswast Oct 26, 2023
bbc3c69
fix: resolve plotly rendering issue by using ipython html for job pro…
orrbradford Oct 26, 2023
a99d62c
refactor: ArrayValue is now a tree that defers conversion to ibis (#110)
TrevorBergeron Oct 27, 2023
f37d0b0
fix: fix bug with column names under repeated column assignment (#150)
milkshakeiii Oct 27, 2023
aba301c
test: refactor remote function tests (#147)
shobsi Oct 27, 2023
53bb2cd
feat: add dataframe melt (#116)
TrevorBergeron Oct 28, 2023
2bf4bcc
docs: add artithmetic df sample code (#153)
ashleyxuu Oct 30, 2023
343414a
feat: Implement operator `@` for `DataFrame.dot` (#139)
shobsi Oct 30, 2023
4eac10d
fix: fix typo and address comments
ashleyxuu Oct 30, 2023
868d2ad
Merge branch 'main' into ashleyxu-add-api-methods
ashleyxuu Oct 30, 2023
c03a8d9
Merge branch 'main' into ashleyxu-add-api-methods
tswast Nov 2, 2023
39321e4
fix: address comments
ashleyxuu Nov 3, 2023
aebcf11
Remove utils folder and refactor it in core directory
ashleyxuu Nov 3, 2023
72217c2
Merge branch 'main' into ashleyxu-add-api-methods
ashleyxuu Nov 3, 2023
ec526b5
Remove utils folder and refactor it in core directory
ashleyxuu Nov 3, 2023
9edfe31
Merge remote-tracking branch 'origin/ashleyxu-add-api-methods' into a…
ashleyxuu Nov 3, 2023
4baa373
Merge branch 'main' into ashleyxu-add-api-methods
ashleyxuu Nov 3, 2023
3a94c23
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Nov 3, 2023
d84c569
fix merge conflicts
ashleyxuu Nov 3, 2023
308c9a7
Merge remote-tracking branch 'origin/ashleyxu-add-api-methods' into a…
ashleyxuu Nov 3, 2023
4618107
commit the conflicts
ashleyxuu Nov 13, 2023
a87bcb8
redesign the log adapter
ashleyxuu Nov 14, 2023
cf97f8b
resolve conflicts and merge remote-tracking branch 'origin/main' into…
ashleyxuu Nov 14, 2023
53a99f9
Make the global _api_methods and lock threads
ashleyxuu Nov 14, 2023
3cc3599
Merge branch 'main' into ashleyxu-add-api-methods
ashleyxuu Nov 14, 2023
1c3deb5
Make the global _api_methods and lock threads
ashleyxuu Nov 14, 2023
99f423b
merge conflicts
ashleyxuu Nov 14, 2023
115de27
address comments
ashleyxuu Nov 14, 2023
b0adf27
address comments
ashleyxuu Nov 14, 2023
b4ea9e3
Merge remote-tracking branch 'origin/ashleyxu-add-api-methods' into a…
ashleyxuu Nov 14, 2023
df9c9c0
fix error
ashleyxuu Nov 14, 2023
00bb6de
fix None job_config error
ashleyxuu Nov 14, 2023
36fea06
address comments
ashleyxuu Nov 14, 2023
e872d18
Merge branch 'main' into ashleyxu-add-api-methods
ashleyxuu Nov 14, 2023
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
Prev Previous commit
Next Next commit
feat: add pandas.qcut (#104)
Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly:
- [ ] Make sure to open an issue as a [bug/issue](https://togithub.com/googleapis/python-bigquery-dataframes/issues/new/choose) before writing your code!  That way we can discuss the change, evaluate designs, and agree on the general idea
- [ ] Ensure the tests and linter pass
- [ ] Code coverage does not decrease (if any source code was changed)
- [ ] Appropriate docs were updated (if necessary)

Fixes #<issue_number_goes_here> 🦕
  • Loading branch information
TrevorBergeron authored and ashleyxuu committed Oct 30, 2023
commit c4c1e6e249878365a8530f4a4164399e4be300bd
33 changes: 33 additions & 0 deletions bigframes/core/reshape/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import bigframes.core as core
import bigframes.core.utils as utils
import bigframes.dataframe
import bigframes.operations as ops
import bigframes.operations.aggregations as agg_ops
import bigframes.series

Expand Down Expand Up @@ -118,3 +119,35 @@ def cut(
f"Only labels=False is supported in BigQuery DataFrames so far. {constants.FEEDBACK_LINK}"
)
return x._apply_window_op(agg_ops.CutOp(bins), window_spec=core.WindowSpec())


def qcut(
x: bigframes.series.Series,
q: typing.Union[int, typing.Sequence[float]],
*,
labels: Optional[bool] = None,
duplicates: typing.Literal["drop", "error"] = "error",
) -> bigframes.series.Series:
if isinstance(q, int) and q <= 0:
raise ValueError("`q` should be a positive integer.")

if labels is not False:
raise NotImplementedError(
f"Only labels=False is supported in BigQuery DataFrames so far. {constants.FEEDBACK_LINK}"
)
if duplicates != "drop":
raise NotImplementedError(
f"Only duplicates='drop' is supported in BigQuery DataFrames so far. {constants.FEEDBACK_LINK}"
)
block = x._block
label = block.col_id_to_label[x._value_column]
block, nullity_id = block.apply_unary_op(x._value_column, ops.notnull_op)
block, result = block.apply_window_op(
x._value_column,
agg_ops.QcutOp(q),
window_spec=core.WindowSpec(grouping_keys=(nullity_id,)),
)
block, result = block.apply_binary_op(
result, nullity_id, ops.partial_arg3(ops.where_op, None), result_label=label
)
return bigframes.series.Series(block.select_column(result))
51 changes: 51 additions & 0 deletions bigframes/operations/aggregations.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,53 @@ def handles_ties(self):
return True


class QcutOp(WindowOp):
def __init__(self, quantiles: typing.Union[int, typing.Sequence[float]]):
self.name = f"qcut-{quantiles}"
self._quantiles = quantiles

@numeric_op
def _as_ibis(
self, column: ibis_types.Column, window=None
) -> ibis_types.IntegerValue:
if isinstance(self._quantiles, int):
quantiles_ibis = dtypes.literal_to_ibis_scalar(self._quantiles)
percent_ranks = typing.cast(
ibis_types.FloatingColumn,
_apply_window_if_present(column.percent_rank(), window),
)
float_bucket = typing.cast(
ibis_types.FloatingColumn, (percent_ranks * quantiles_ibis)
)
return float_bucket.ceil().clip(lower=_ibis_num(1)) - _ibis_num(1)
else:
percent_ranks = typing.cast(
ibis_types.FloatingColumn,
_apply_window_if_present(column.percent_rank(), window),
)
out = ibis.case()
first_ibis_quantile = dtypes.literal_to_ibis_scalar(self._quantiles[0])
out = out.when(percent_ranks < first_ibis_quantile, None)
for bucket_n in range(len(self._quantiles) - 1):
ibis_quantile = dtypes.literal_to_ibis_scalar(
self._quantiles[bucket_n + 1]
)
out = out.when(
percent_ranks <= ibis_quantile,
dtypes.literal_to_ibis_scalar(bucket_n, force_dtype=Int64Dtype()),
)
out = out.else_(None)
return out.end()

@property
def skips_nulls(self):
return False

@property
def handles_ties(self):
return True


class NuniqueOp(AggregateOp):
name = "nunique"

Expand Down Expand Up @@ -491,3 +538,7 @@ def lookup_agg_func(key: str) -> AggregateOp:
return _AGGREGATIONS_LOOKUP[key]
else:
raise ValueError(f"Unrecognize aggregate function: {key}")


def _ibis_num(number: float):
return typing.cast(ibis_types.NumericValue, ibis_types.literal(number))
13 changes: 13 additions & 0 deletions bigframes/pandas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,19 @@ def cut(
cut.__doc__ = vendored_pandas_tile.cut.__doc__


def qcut(
x: bigframes.series.Series,
q: int,
*,
labels: Optional[bool] = None,
duplicates: typing.Literal["drop", "error"] = "error",
) -> bigframes.series.Series:
return bigframes.core.reshape.qcut(x, q, labels=labels, duplicates=duplicates)


qcut.__doc__ = vendored_pandas_tile.qcut.__doc__


def merge(
left: DataFrame,
right: DataFrame,
Expand Down
25 changes: 25 additions & 0 deletions tests/system/small/test_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,28 @@ def test_cut(scalars_dfs):
bf_result = bf_result.to_pandas()
pd_result = pd_result.astype("Int64")
pd.testing.assert_series_equal(bf_result, pd_result)


@pytest.mark.parametrize(
("q",),
[
(1,),
(2,),
(7,),
(32,),
([0, 0.1, 0.3, 0.4, 0.9, 1.0],),
([0.5, 0.9],),
],
)
def test_qcut(scalars_dfs, q):
scalars_df, scalars_pandas_df = scalars_dfs

pd_result = pd.qcut(
scalars_pandas_df["float64_col"], q, labels=False, duplicates="drop"
)
bf_result = bpd.qcut(scalars_df["float64_col"], q, labels=False, duplicates="drop")

bf_result = bf_result.to_pandas()
pd_result = pd_result.astype("Int64")

pd.testing.assert_series_equal(bf_result, pd_result)
30 changes: 30 additions & 0 deletions third_party/bigframes_vendored/pandas/core/reshape/tile.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,33 @@ def cut(
False : returns an ndarray of integers.
"""
raise NotImplementedError(constants.ABSTRACT_METHOD_ERROR_MESSAGE)


def qcut(x, q, *, labels=None, duplicates="error"):
"""
Quantile-based discretization function.

Discretize variable into equal-sized buckets based on rank or based
on sample quantiles. For example 1000 values for 10 quantiles would
produce a Categorical object indicating quantile membership for each data point.

Args:
x (Series):
The input Series to be binned. Must be 1-dimensional.
q (int or list-like of float):
Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately
array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles.
labels (None):
Used as labels for the resulting bins. Must be of the same length as
the resulting bins. If False, return only integer indicators of the
bins. If True, raises an error.
duplicates ({default 'raise', 'drop'}, optional):
If bin edges are not unique, raise ValueError or drop non-uniques.

Returns:
Series: Categorical or Series of integers if labels is False
The return type (Categorical or Series) depends on the input: a Series
of type category if input is a Series else Categorical. Bins are
represented as categories when categorical data is returned.
"""
raise NotImplementedError(constants.ABSTRACT_METHOD_ERROR_MESSAGE)