1
---
2
name: bigquery-bigframes
3
metadata:
4
version: "2.0.1"
5
category: BigDataAndAnalytics
6
description: >-
7
Generates Python code using BigQuery DataFrames (BigFrames). Use by default for any Python data task involving BigQuery, including data processing, analysis, and machine learning. Don't use for SQL-first workflows or the google-cloud-bigquery client library — use bigquery-basics.
8
9
---
10
11
# BigFrames (BigQuery DataFrame) basics
12
BigFrames is a Python library that lets you take advantage of BigQuery
13
data processing by using familiar Python APIs.
14
15
## Attribution
16
17
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
18
MUST read [Usage Attribution](references/attribution.md). For commands executed
19
directly in the terminal (never in generated scripts, Terraform, or user code),
20
prefix `gcloud` with
21
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-bigframes)"`
22
and append `agent-skills/1.0 (skill:bigquery-bigframes)` to `User-Agent` headers.
23
24
## Dataframe API best practices
25
26
* **Stay in the Cloud**: Perform data cleaning, transformation, and analysis
27
via BigFrames methods to leverage BigQuery's scale rather than downloading
28
data.
29
* **Prefer partial ordering mode**: Enable partial ordering mode right after
30
importing BigFrames. This speeds up data processing significantly by relaxing
31
row-sequence constraints.
32
33
```python
34
import bigframes.pandas as bpd
35
bpd.options.bigquery.ordering_mode = 'partial'
36
```
37
* **Use `peek()` for data preview**: Use `peek(n)` to preview data instead of
38
`head(n)`. `peek(n)` randomly samples `n` rows and is significantly faster.
39
`head(n)` returns rows in strict order and fails in `partial` ordering mode
40
unless the DataFrame has been explicitly sorted.
41
* **Avoid materializing data locally**: Methods like `to_pandas()` download all
42
data to client memory, bypassing BigQuery’s distributed computation and
43
risking Out of Memory (OOM) errors. Do not materialize data locally unless:
44
* The dataset is small enough to fit safely in memory.
45
* An error message explicitly requires local materialization.
46
* **Prefer Dataframe API over SQL queries**: Do not write raw SQL queries via
47
`read_gbq()` if a DataFrame/Series method achieves the same result, as it
48
breaks the Pandas abstraction and prevents lazy query execution.
49
* **Accessors over UDFs/Lambdas**:
50
* Use built-in accessors (e.g., `df.col.str.*`, `df.col.dt.*`) instead of
51
remote User Defined Functions (UDFs). UDFs require extra resources and
52
time to deploy.
53
* Do not use lambdas with `Series.map()` or `DataFrame.apply()`. These
54
methods do not accept functions without `udf` or `remote_function`
55
decorators.
56
```python
57
# Avoid:
58
df["upper"] = df["name"].map(lambda x: x.upper())
59
60
# Prefer:
61
df["upper"] = df["name"].str.upper()
62
```
63
* **Schema Verification**: Do not assume the schema of intermediate outputs.
64
Proactively verify schemas using `.dtypes` and inspect sample records using
65
`display()` with `.peek()`.
66
* **Visualization**: Plot directly from the BigFrames DataFrame/Series when
67
possible. BigFrames is compatible with Matplotlib and Seaborn. If direct
68
plotting fails, use the `.plot` accessor. If the dataset is too large to plot,
69
aggregate or sample the data before calling
70
`.to_pandas()` to plot locally.
71
72
## Machine Learning
73
* **Use `bigframes.bigquery.ml` package**: Do not use Scikit-learn or other ML
74
libraries with BigQuery DataFrames. Standard Scikit-learn models require
75
bringing data into local client memory, whereas `bigframes.bigquery.ml`
76
delegates training directly to BigQuery's scalable ML engine. Import functions
77
from `bigframes.bigquery.ml`.
78
79
### Reference Directory
80
* [Linear Regression](references/linear_regression.md): Train a linear
81
regression model to predict numerical values.
82
* [Logistic Regression](references/logistic_regression.md): Train a logistic
83
regression model to predict boolean values.
84
85
## BigFrames ML (Legacy)
86
87
The BigFrames ML package (`bigframes.ml`) is a legacy package that mimics the
88
scikit-learn API but is no longer recommended for new projects. Only use this
89
package if the user explicitly requests BigFrames ML.
90
91
* **Legacy Imports**: When legacy BigFrames ML is requested, import tools and
92
classes from `bigframes.ml` instead of `bigframes.bigquery.ml`.
93
* **DataFrame Return on Prediction**: Unlike Scikit-learn, BigFrames'
94
`predict()` method always returns a **DataFrame** containing both predictions
95
and features, rather than a single series of predictions.
96
* **No `random_state`**: Do not pass a `random_state` argument when
97
instantiating BigFrames ML models, as this parameter is not supported in the
98
BigFrames ML package.
99
* **Automatic Scaling**: Do not use `OneHotEncoder` or `StandardScaler` unless
100
explicitly requested, as scaling is handled automatically.
101
* **Hyperparameter Tuning**: Write custom loops for hyperparameter tuning, as
102
BigFrames lacks `GridSearchCV` or `RandomizedSearchCV`.
103
* **ARIMA Plus** (Forecasting):
104
* Import from `bigframes.ml.forecasting`.
105
* Sort data chronologically and split around a timepoint before training.
106
* Ensure the prediction horizon is less than or equal to the training
107
horizon.
108
* **PCA**: BigFrames' PCA class lacks a `transform()` method. Use `predict()`
109
instead.
110
* **Model Persistence**: To persist a model, use `model.to_gbq()`. To load a
111
persisted model, use `bpd.read_gbq_model()`.
112