Skip to content

Commit d2710c2

Browse files
committed
Merge branch 'main' into shuowei-anywidget-nested-strcut-array
2 parents fb2d029 + 6fef9be commit d2710c2

File tree

70 files changed

+1887
-232
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

70 files changed

+1887
-232
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,4 @@ tests/js/node_modules/
6464
pylintrc
6565
pylintrc.test
6666
dummy.pkl
67+
.mypy_cache/

.librarian/state.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
image: us-central1-docker.pkg.dev/cloud-sdk-librarian-prod/images-prod/python-librarian-generator@sha256:c8612d3fffb3f6a32353b2d1abd16b61e87811866f7ec9d65b59b02eb452a620
1+
image: us-central1-docker.pkg.dev/cloud-sdk-librarian-prod/images-prod/python-librarian-generator@sha256:e7cc6823efb073a8a26e7cefdd869f12ec228abfbd2a44aa9a7eacc284023677
22
libraries:
33
- id: bigframes
4-
version: 2.32.0
4+
version: 2.33.0
55
last_generated_commit: ""
66
apis: []
77
source_roots:

CHANGELOG.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,24 @@
44

55
[1]: https://pypi.org/project/bigframes/#history
66

7+
## [2.33.0](https://github.com/googleapis/python-bigquery-dataframes/compare/v2.32.0...v2.33.0) (2026-01-22)
8+
9+
10+
### Features
11+
12+
* add bigquery.ml.transform function (#2394) ([1f9ee373c1f1d0cd08b80169c3063b862ea46465](https://github.com/googleapis/python-bigquery-dataframes/commit/1f9ee373c1f1d0cd08b80169c3063b862ea46465))
13+
* Add BigQuery ObjectRef functions to `bigframes.bigquery.obj` (#2380) ([9c3bbc36983dffb265454f27b37450df8c5fbc71](https://github.com/googleapis/python-bigquery-dataframes/commit/9c3bbc36983dffb265454f27b37450df8c5fbc71))
14+
* Stabilize interactive table height to prevent notebook layout shifts (#2378) ([a634e976c0f44087ca2a65f68cf2775ae6f04024](https://github.com/googleapis/python-bigquery-dataframes/commit/a634e976c0f44087ca2a65f68cf2775ae6f04024))
15+
* Add max_columns control for anywidget mode (#2374) ([34b5975f6911c5aa5ffc64a2fe6967a9f3d86f78](https://github.com/googleapis/python-bigquery-dataframes/commit/34b5975f6911c5aa5ffc64a2fe6967a9f3d86f78))
16+
* Add dark mode to anywidget mode (#2365) ([2763b41d4b86939e389f76789f5b2acd44f18169](https://github.com/googleapis/python-bigquery-dataframes/commit/2763b41d4b86939e389f76789f5b2acd44f18169))
17+
* Configure Biome for Consistent Code Style (#2364) ([81e27b3d81da9b1684eae0b7f0b9abfd7badcc4f](https://github.com/googleapis/python-bigquery-dataframes/commit/81e27b3d81da9b1684eae0b7f0b9abfd7badcc4f))
18+
19+
20+
### Bug Fixes
21+
22+
* Throw if write api commit op has stream_errors (#2385) ([7abfef0598d476ef233364a01f72d73291983c30](https://github.com/googleapis/python-bigquery-dataframes/commit/7abfef0598d476ef233364a01f72d73291983c30))
23+
* implement retry logic for cloud function endpoint fetching (#2369) ([0f593c27bfee89fe1bdfc880504f9ab0ac28a24e](https://github.com/googleapis/python-bigquery-dataframes/commit/0f593c27bfee89fe1bdfc880504f9ab0ac28a24e))
24+
725
## [2.32.0](https://github.com/googleapis/google-cloud-python/compare/bigframes-v2.31.0...bigframes-v2.32.0) (2026-01-05)
826

927

bigframes/bigquery/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
import sys
2020

21-
from bigframes.bigquery import ai, ml
21+
from bigframes.bigquery import ai, ml, obj
2222
from bigframes.bigquery._operations.approx_agg import approx_top_count
2323
from bigframes.bigquery._operations.array import (
2424
array_agg,
@@ -158,4 +158,5 @@
158158
# Modules / SQL namespaces
159159
"ai",
160160
"ml",
161+
"obj",
161162
]

bigframes/bigquery/_operations/ai.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,14 @@ def generate(
5858
>>> import bigframes.pandas as bpd
5959
>>> import bigframes.bigquery as bbq
6060
>>> country = bpd.Series(["Japan", "Canada"])
61-
>>> bbq.ai.generate(("What's the capital city of ", country, " one word only"))
62-
0 {'result': 'Tokyo\\n', 'full_response': '{"cand...
63-
1 {'result': 'Ottawa\\n', 'full_response': '{"can...
61+
>>> bbq.ai.generate(("What's the capital city of ", country, " one word only")) # doctest: +SKIP
62+
0 {'result': 'Tokyo', 'full_response': '{"cand...
63+
1 {'result': 'Ottawa', 'full_response': '{"can...
6464
dtype: struct<result: string, full_response: extension<dbjson<JSONArrowType>>, status: string>[pyarrow]
6565
66-
>>> bbq.ai.generate(("What's the capital city of ", country, " one word only")).struct.field("result")
67-
0 Tokyo\\n
68-
1 Ottawa\\n
66+
>>> bbq.ai.generate(("What's the capital city of ", country, " one word only")).struct.field("result") # doctest: +SKIP
67+
0 Tokyo
68+
1 Ottawa
6969
Name: result, dtype: string
7070
7171
You get structured output when the `output_schema` parameter is set:

bigframes/bigquery/_operations/ml.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,3 +393,41 @@ def global_explain(
393393
return bpd.read_gbq_query(sql)
394394
else:
395395
return session.read_gbq_query(sql)
396+
397+
398+
@log_adapter.method_logger(custom_base_name="bigquery_ml")
399+
def transform(
400+
model: Union[bigframes.ml.base.BaseEstimator, str, pd.Series],
401+
input_: Union[pd.DataFrame, dataframe.DataFrame, str],
402+
) -> dataframe.DataFrame:
403+
"""
404+
Transforms input data using a BigQuery ML model.
405+
406+
See the `BigQuery ML TRANSFORM function syntax
407+
<https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/bigqueryml-syntax-transform>`_
408+
for additional reference.
409+
410+
Args:
411+
model (bigframes.ml.base.BaseEstimator or str):
412+
The model to use for transformation.
413+
input_ (Union[bigframes.pandas.DataFrame, str]):
414+
The DataFrame or query to use for transformation.
415+
416+
Returns:
417+
bigframes.pandas.DataFrame:
418+
The transformed data.
419+
"""
420+
import bigframes.pandas as bpd
421+
422+
model_name, session = _get_model_name_and_session(model, input_)
423+
table_sql = _to_sql(input_)
424+
425+
sql = bigframes.core.sql.ml.transform(
426+
model_name=model_name,
427+
table=table_sql,
428+
)
429+
430+
if session is None:
431+
return bpd.read_gbq_query(sql)
432+
else:
433+
return session.read_gbq_query(sql)
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
16+
"""This module exposes BigQuery ObjectRef functions.
17+
18+
See bigframes.bigquery.obj for public docs.
19+
"""
20+
21+
22+
from __future__ import annotations
23+
24+
import datetime
25+
from typing import Optional, Sequence, Union
26+
27+
import numpy as np
28+
import pandas as pd
29+
30+
from bigframes.core import convert
31+
from bigframes.core.logging import log_adapter
32+
import bigframes.core.utils as utils
33+
import bigframes.operations as ops
34+
import bigframes.series as series
35+
36+
37+
@log_adapter.method_logger(custom_base_name="bigquery_obj")
38+
def fetch_metadata(
39+
objectref: series.Series,
40+
) -> series.Series:
41+
"""[Preview] The OBJ.FETCH_METADATA function returns Cloud Storage metadata for a partially populated ObjectRef value.
42+
43+
Args:
44+
objectref (bigframes.pandas.Series):
45+
A partially populated ObjectRef value, in which the uri and authorizer fields are populated and the details field isn't.
46+
47+
Returns:
48+
bigframes.pandas.Series: A fully populated ObjectRef value. The metadata is provided in the details field of the returned ObjectRef value.
49+
"""
50+
objectref = convert.to_bf_series(objectref, default_index=None)
51+
return objectref._apply_unary_op(ops.obj_fetch_metadata_op)
52+
53+
54+
@log_adapter.method_logger(custom_base_name="bigquery_obj")
55+
def get_access_url(
56+
objectref: series.Series,
57+
mode: str,
58+
duration: Optional[Union[datetime.timedelta, pd.Timedelta, np.timedelta64]] = None,
59+
) -> series.Series:
60+
"""[Preview] The OBJ.GET_ACCESS_URL function returns JSON that contains reference information for the input ObjectRef value, and also access URLs that you can use to read or modify the Cloud Storage object.
61+
62+
Args:
63+
objectref (bigframes.pandas.Series):
64+
An ObjectRef value that represents a Cloud Storage object.
65+
mode (str):
66+
A STRING value that identifies the type of URL that you want to be returned. The following values are supported:
67+
'r': Returns a URL that lets you read the object.
68+
'rw': Returns two URLs, one that lets you read the object, and one that lets you modify the object.
69+
duration (Union[datetime.timedelta, pandas.Timedelta, numpy.timedelta64], optional):
70+
An optional INTERVAL value that specifies how long the generated access URLs remain valid. You can specify a value between 30 minutes and 6 hours. For example, you could specify INTERVAL 2 HOUR to generate URLs that expire after 2 hours. The default value is 6 hours.
71+
72+
Returns:
73+
bigframes.pandas.Series: A JSON value that contains the Cloud Storage object reference information from the input ObjectRef value, and also one or more URLs that you can use to access the Cloud Storage object.
74+
"""
75+
objectref = convert.to_bf_series(objectref, default_index=None)
76+
77+
duration_micros = None
78+
if duration is not None:
79+
duration_micros = utils.timedelta_to_micros(duration)
80+
81+
return objectref._apply_unary_op(
82+
ops.ObjGetAccessUrl(mode=mode, duration=duration_micros)
83+
)
84+
85+
86+
@log_adapter.method_logger(custom_base_name="bigquery_obj")
87+
def make_ref(
88+
uri_or_json: Union[series.Series, Sequence[str]],
89+
authorizer: Union[series.Series, str, None] = None,
90+
) -> series.Series:
91+
"""[Preview] Use the OBJ.MAKE_REF function to create an ObjectRef value that contains reference information for a Cloud Storage object.
92+
93+
Args:
94+
uri_or_json (bigframes.pandas.Series or str):
95+
A series of STRING values that contains the URI for the Cloud Storage object, for example, gs://mybucket/flowers/12345.jpg.
96+
OR
97+
A series of JSON value that represents a Cloud Storage object.
98+
authorizer (bigframes.pandas.Series or str, optional):
99+
A STRING value that contains the Cloud Resource connection used to access the Cloud Storage object.
100+
Required if ``uri_or_json`` is a URI string.
101+
102+
Returns:
103+
bigframes.pandas.Series: An ObjectRef value.
104+
"""
105+
uri_or_json = convert.to_bf_series(uri_or_json, default_index=None)
106+
107+
if authorizer is not None:
108+
# Avoid join problems encountered if we try to convert a literal into Series.
109+
if not isinstance(authorizer, str):
110+
authorizer = convert.to_bf_series(authorizer, default_index=None)
111+
112+
return uri_or_json._apply_binary_op(authorizer, ops.obj_make_ref_op)
113+
114+
# If authorizer is not provided, we assume uri_or_json is a JSON objectref
115+
return uri_or_json._apply_unary_op(ops.obj_make_ref_json_op)

bigframes/bigquery/ml.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
explain_predict,
2626
global_explain,
2727
predict,
28+
transform,
2829
)
2930

3031
__all__ = [
@@ -33,4 +34,5 @@
3334
"predict",
3435
"explain_predict",
3536
"global_explain",
37+
"transform",
3638
]

bigframes/bigquery/obj.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""This module integrates BigQuery built-in 'ObjectRef' functions for use with Series/DataFrame objects,
16+
such as OBJ.FETCH_METADATA:
17+
https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/objectref_functions
18+
19+
20+
.. warning::
21+
22+
This product or feature is subject to the "Pre-GA Offerings Terms" in the
23+
General Service Terms section of the `Service Specific Terms
24+
<https://cloud.google.com/terms/service-terms>`_. Pre-GA products and
25+
features are available "as is" and might have limited support. For more
26+
information, see the `launch stage descriptions
27+
<https://cloud.google.com/products?hl=en#product-launch-stages>`_.
28+
29+
.. note::
30+
31+
To provide feedback or request support for this feature, send an email to
32+
bq-objectref-feedback@google.com.
33+
"""
34+
35+
from bigframes.bigquery._operations.obj import fetch_metadata, get_access_url, make_ref
36+
37+
__all__ = [
38+
"fetch_metadata",
39+
"get_access_url",
40+
"make_ref",
41+
]

bigframes/core/blocks.py

Lines changed: 23 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -818,49 +818,30 @@ def _materialize_local(
818818
total_rows = result_batches.approx_total_rows
819819
# Remove downsampling config from subsequent invocations, as otherwise could result in many
820820
# iterations if downsampling undershoots
821-
return self._downsample(
822-
total_rows=total_rows,
823-
sampling_method=sample_config.sampling_method,
824-
fraction=fraction,
825-
random_state=sample_config.random_state,
826-
)._materialize_local(
827-
MaterializationOptions(ordered=materialize_options.ordered)
828-
)
829-
else:
830-
df = result_batches.to_pandas()
831-
df = self._copy_index_to_pandas(df)
832-
df.set_axis(self.column_labels, axis=1, copy=False)
833-
return df, execute_result.query_job
834-
835-
def _downsample(
836-
self, total_rows: int, sampling_method: str, fraction: float, random_state
837-
) -> Block:
838-
# either selecting fraction or number of rows
839-
if sampling_method == _HEAD:
840-
filtered_block = self.slice(stop=int(total_rows * fraction))
841-
return filtered_block
842-
elif (sampling_method == _UNIFORM) and (random_state is None):
843-
filtered_expr = self.expr._uniform_sampling(fraction)
844-
block = Block(
845-
filtered_expr,
846-
index_columns=self.index_columns,
847-
column_labels=self.column_labels,
848-
index_labels=self.index.names,
849-
)
850-
return block
851-
elif sampling_method == _UNIFORM:
852-
block = self.split(
853-
fracs=(fraction,),
854-
random_state=random_state,
855-
sort=False,
856-
)[0]
857-
return block
821+
if sample_config.sampling_method == "head":
822+
# Just truncates the result iterator without a follow-up query
823+
raw_df = result_batches.to_pandas(limit=int(total_rows * fraction))
824+
elif (
825+
sample_config.sampling_method == "uniform"
826+
and sample_config.random_state is None
827+
):
828+
# Pushes sample into result without new query
829+
sampled_batches = execute_result.batches(sample_rate=fraction)
830+
raw_df = sampled_batches.to_pandas()
831+
else: # uniform sample with random state requires a full follow-up query
832+
down_sampled_block = self.split(
833+
fracs=(fraction,),
834+
random_state=sample_config.random_state,
835+
sort=False,
836+
)[0]
837+
return down_sampled_block._materialize_local(
838+
MaterializationOptions(ordered=materialize_options.ordered)
839+
)
858840
else:
859-
# This part should never be called, just in case.
860-
raise NotImplementedError(
861-
f"The downsampling method {sampling_method} is not implemented, "
862-
f"please choose from {','.join(_SAMPLING_METHODS)}."
863-
)
841+
raw_df = result_batches.to_pandas()
842+
df = self._copy_index_to_pandas(raw_df)
843+
df.set_axis(self.column_labels, axis=1, copy=False)
844+
return df, execute_result.query_job
864845

865846
def split(
866847
self,

0 commit comments

Comments
 (0)