Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
37 changes: 31 additions & 6 deletions packages/bigframes/bigframes/core/col.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from typing import TYPE_CHECKING, Any, Hashable, Literal

import bigframes_vendored.pandas.core.col as pd_col
import numpy

import bigframes.core.expression as bf_expression
import bigframes.operations as bf_ops
Expand Down Expand Up @@ -56,14 +57,10 @@ def _apply_binary_op(
alignment: Literal["outer", "left"] = "outer",
reverse: bool = False,
):
if isinstance(other, Expression):
other_value = other._value
else:
other_value = bf_expression.const(other)
if reverse:
return Expression(op.as_expr(other_value, self._value))
return Expression(op.as_expr(_as_bf_expr(other), self._value))
else:
return Expression(op.as_expr(self._value, other_value))
return Expression(op.as_expr(self._value, _as_bf_expr(other)))

def __add__(self, other: Any) -> Expression:
return self._apply_binary_op(other, bf_ops.add_op)
Expand Down Expand Up @@ -170,6 +167,34 @@ def str(self) -> strings.StringMethods:

return strings.StringMethods(self)

def __array_ufunc__(
self, ufunc: numpy.ufunc, method: __builtins__.str, *inputs, **kwargs
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Using __builtins__.str as a type hint is non-standard and potentially fragile. It is recommended to use the built-in str type directly.

Suggested change
self, ufunc: numpy.ufunc, method: __builtins__.str, *inputs, **kwargs
self, ufunc: numpy.ufunc, method: str, *inputs, **kwargs
References
  1. Standard Python type hinting practices (PEP 484) recommend using built-in types like 'str' directly instead of accessing them through 'builtins'. (link)

) -> Expression:
"""Used to support numpy ufuncs.
See: https://numpy.org/doc/stable/reference/ufuncs.html
"""
# Only __call__ supported with zero arguments
if method != "__call__" or len(inputs) > 2 or len(kwargs) > 0:
return NotImplemented

if len(inputs) == 1 and ufunc in bf_ops.NUMPY_TO_OP:
op = bf_ops.NUMPY_TO_OP[ufunc]
return Expression(op.as_expr(self._value))
if len(inputs) == 2 and ufunc in bf_ops.NUMPY_TO_BINOP:
binop = bf_ops.NUMPY_TO_BINOP[ufunc]
if inputs[0] is self:
return Expression(binop.as_expr(self._value, _as_bf_expr(inputs[1])))
else:
return Expression(binop.as_expr(_as_bf_expr(inputs[0]), self._value))

return NotImplemented


def _as_bf_expr(arg: Any) -> bf_expression.Expression:
if isinstance(arg, Expression):
return arg._value
return bf_expression.const(arg)


def col(col_name: Hashable) -> Expression:
return Expression(bf_expression.free_var(col_name))
Expand Down
24 changes: 24 additions & 0 deletions packages/bigframes/tests/unit/test_col.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import bigframes
import bigframes.pandas as bpd
from bigframes.testing.utils import assert_frame_equal, convert_pandas_dtypes
import numpy as np

pytest.importorskip("polars")
pytest.importorskip("pandas", minversion="3.0.0")
Expand Down Expand Up @@ -246,3 +247,26 @@ def test_col_dt_accessor(scalars_dfs):

# int64[pyarrow] vs Int64
assert_frame_equal(bf_result, pd_result, check_dtype=False)


def test_col_numpy_ufunc(scalars_dfs):
scalars_df, scalars_pandas_df = scalars_dfs

bf_kwargs = {
"sqrt": np.sqrt(bpd.col("float64_col")), # type: ignore
"add_const": np.add(bpd.col("float64_col"), 2.4), # type: ignore
"radd_const": np.add(2.4, bpd.col("float64_col")), # type: ignore
"add_cols": np.add(bpd.col("float64_col"), bpd.col("int64_col")), # type: ignore
}
pd_kwargs = {
"sqrt": np.sqrt(pd.col("float64_col")), # type: ignore
"add_const": np.add(pd.col("float64_col"), 2.4), # type: ignore
"radd_const": np.add(2.4, pd.col("float64_col")), # type: ignore
"add_cols": np.add(pd.col("float64_col"), pd.col("int64_col")), # type: ignore
}
Comment on lines +261 to +266
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The pd_kwargs dictionary uses pd.col, which is not a standard pandas API. To correctly verify the BigFrames implementation against pandas, the expected results should be computed using standard pandas column access on scalars_pandas_df. Additionally, standard pandas assign does not support BigFrames Expression objects. To ensure dictionary keys remain sorted without manual effort, the dictionary should be programmatically sorted.

Suggested change
pd_kwargs = {
"sqrt": np.sqrt(pd.col("float64_col")), # type: ignore
"add_const": np.add(pd.col("float64_col"), 2.4), # type: ignore
"radd_const": np.add(2.4, pd.col("float64_col")), # type: ignore
"add_cols": np.add(pd.col("float64_col"), pd.col("int64_col")), # type: ignore
}
pd_kwargs = dict(sorted({
"sqrt": np.sqrt(scalars_pandas_df["float64_col"]),
"add_const": np.add(scalars_pandas_df["float64_col"], 2.4),
"radd_const": np.add(2.4, scalars_pandas_df["float64_col"]),
"add_cols": np.add(scalars_pandas_df["float64_col"], scalars_pandas_df["int64_col"]),
}.items()))
References
  1. To ensure dictionary keys remain sorted without manual effort, programmatically sort the dictionary instead of relying on manual ordering in the code.


bf_result = scalars_df.assign(**bf_kwargs).to_pandas()
pd_result = scalars_pandas_df.assign(**pd_kwargs) # type: ignore

# int64[pyarrow] vs Int64
assert_frame_equal(bf_result, pd_result, check_dtype=False)
Loading