使用 BigQuery DataFrames

若要在预览版期间获得支持,请发送电子邮件至 bigframes-feedback@google.com

本文档介绍如何使用 BigQuery DataFrames 分析和操作 BigQuery 笔记本中的数据。

BigQuery DataFrames 是一个 Python 客户端库,可用于在 BigQuery 笔记本中分析数据和执行机器学习任务。

BigQuery DataFrames 包含以下部分:

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  4. 确保您的 Google Cloud 项目已启用结算功能

  5. 确保已启用 BigQuery API。

    启用 API

    如果您创建了一个新项目,则系统会自动启用 BigQuery API。

所需权限

如需在 BigQuery 笔记本中使用 BigQuery DataFrames,您需要以下 Identity and Access Management (IAM) 角色:

创建笔记本

按照通过 BigQuery 编辑器创建笔记本中的说明创建新的笔记本。

设置 BigQuery DataFrames 选项

安装完成后,您需要指定要在其中使用 BigQuery DataFrames 的位置项目

您可以通过以下方式在笔记本中定义位置和项目:

import bigframes.pandas as bpd

PROJECT_ID = "bigframes-dec"  # @param {type:"string"}
REGION = "US"  # @param {type:"string"}

# Set BigQuery DataFrames options
bpd.options.bigquery.project = PROJECT_ID
bpd.options.bigquery.location = REGION

使用 bigframes.pandas

bigframes.pandas API 提供类似于 pandas 的 API,可用于分析和操作 BigQuery 中的数据。bigframes.pandas API 可以扩缩,支持处理 TB 级的 BigQuery 数据,并使用 BigQuery 查询引擎执行计算。

bigframes.pandas API 提供以下功能:

输入和输出
您可以从各种来源访问数据,包括本地 CSV 文件、Cloud Storage 文件、pandas DataFrame、BigQuery 模型和 BigQuery 函数,并将其加载到 BigQuery DataFrame 中。您还可以从 BigQuery DataFrames 创建 BigQuery 表。
数据操作
您可以使用 Python(而不是 SQL)进行开发。您可以使用 Python 开发所有 BigQuery 数据操作,无需在语言之间切换并尝试以文本字符串形式捕获 SQL 语句。bigframes.pandas API 提供超过 250 个 pandas 函数。
Python 生态系统和可视化
bigframes.pandas API 是完整的 Python 工具生态系统的网关。此 API 支持高级统计操作,您可以直观呈现从 BigQuery DataFrames 生成的聚合。您还可以使用内置的采样操作从 BigQuery DataFrame 切换到 pandas DataFrame。
自定义 Python 函数
您可以使用自定义 Python 函数和软件包。借助 bigframes.pandas,您可以部署以 BigQuery 规模运行标量 Python 函数的远程函数。您可以将这些函数作为 SQL 例程保留回 BigQuery,并像使用 SQL 函数一样使用它们。

从 BigQuery 表或查询加载数据

您可以通过以下方式从 BigQuery 表或查询创建 DataFrame:

# Create a DataFrame from a BigQuery table:
import bigframes.pandas as bpd

query_or_table = "bigquery-public-data.ml_datasets.penguins"
bq_df = bpd.read_gbq(query_or_table)

从 CSV 文件加载数据

您可以通过以下方式从本地或 Cloud Storage CSV 文件创建 DataFrame:

import bigframes.pandas as bpd

filepath_or_buffer = "gs://cloud-samples-data/bigquery/us-states/us-states.csv"
df_from_gcs = bpd.read_csv(filepath_or_buffer)
# Display the first few rows of the DataFrame:
df_from_gcs.head()

检查和操纵数据

您可以使用 bigframes.pandas 执行数据检查和计算操作。

以下代码示例展示如何使用 bigframes.pandas 检查 body_mass_g 列,计算平均值 body_mass,以及按 species 计算平均值 body_mass

import bigframes.pandas as bpd

# Load data from BigQuery
query_or_table = "bigquery-public-data.ml_datasets.penguins"
bq_df = bpd.read_gbq(query_or_table)

# Inspect one of the columns (or series) of the DataFrame:
bq_df["body_mass_g"]

# Compute the mean of this series:
average_body_mass = bq_df["body_mass_g"].mean()
print(f"average_body_mass: {average_body_mass}")

# Find the heaviest species using the groupby operation to calculate the
# mean body_mass_g:
(
    bq_df["body_mass_g"]
    .groupby(by=bq_df["species"])
    .mean()
    .sort_values(ascending=False)
    .head(10)
)

使用 bigframes.ml

借助 bigframes.ml 类似 scikit-learn 的 API,您可以创建多种类型的机器学习模型。

回归

以下代码示例展示如何使用 bigframes.ml 执行以下操作:

from bigframes.ml.linear_model import LinearRegression
import bigframes.pandas as bpd

# Load data from BigQuery
query_or_table = "bigquery-public-data.ml_datasets.penguins"
bq_df = bpd.read_gbq(query_or_table)

# Filter down to the data to the Adelie Penguin species
adelie_data = bq_df[bq_df.species == "Adelie Penguin (Pygoscelis adeliae)"]

# Drop the species column
adelie_data = adelie_data.drop(columns=["species"])

# Drop rows with nulls to get training data
training_data = adelie_data.dropna()

# Specify your feature (or input) columns and the label (or output) column:
feature_columns = training_data[
    ["island", "culmen_length_mm", "culmen_depth_mm", "flipper_length_mm", "sex"]
]
label_columns = training_data[["body_mass_g"]]

test_data = adelie_data[adelie_data.body_mass_g.isnull()]

# Create the linear model
model = LinearRegression()
model.fit(feature_columns, label_columns)

# Score the model
score = model.score(feature_columns, label_columns)

# Predict using the model
result = model.predict(test_data)

聚簇

您可以使用 bigframes.ml.cluster 模块为聚类模型创建 Estimator。

以下代码示例展示如何使用 bigframes.ml.clusterKMeans 类创建用于数据细分的 K-means 聚类模型:

from bigframes.ml.cluster import KMeans
import bigframes.pandas as bpd

# Load data from BigQuery
query_or_table = "bigquery-public-data.ml_datasets.penguins"
bq_df = bpd.read_gbq(query_or_table)

# Create the KMeans model
cluster_model = KMeans(n_clusters=10)
cluster_model.fit(bq_df["culmen_length_mm"], bq_df["sex"])

# Predict using the model
result = cluster_model.predict(bq_df)
# Score the model
score = cluster_model.score(bq_df)

LLM 远程模型

您可以使用 bigframes.ml.llm 模块为远程大语言模型 (LLM) 创建 Estimator。

以下代码示例展示如何使用 bigframes.ml.llmPaLM2TextGenerator 类创建用于文本生成的 PaLM2 文本生成器模型:

from bigframes.ml.llm import PaLM2TextGenerator
import bigframes.pandas as bpd

# Create the LLM model
session = bpd.get_global_session()
connection = f"{PROJECT_ID}.{REGION}.{CONN_NAME}"
model = PaLM2TextGenerator(session=session, connection_name=connection)

df_api = bpd.read_csv("gs://cloud-samples-data/vertex-ai/bigframe/df.csv")

# Prepare the prompts and send them to the LLM model for prediction
df_prompt_prefix = "Generate Pandas sample code for DataFrame."
df_prompt = df_prompt_prefix + df_api["API"]

# Predict using the model
df_pred = model.predict(df_prompt.to_frame(), max_output_tokens=1024)

价格

BigQuery DataFrames 是一个开源 Python 库。源代码可通过 GitHub 查看和下载。您可以从 PyPI 安装该库。此库也可能在由社区管理的其他软件包管理系统中获得。

BigQuery DataFrames 使用 BigQueryCloud FunctionsVertex AI 和其他 Google Cloud 服务,这些服务会产生各自的费用。在常规使用期间,该库会将数据存储在中间 BigQuery 表中,这些表中默认有效期为 7 天。

后续步骤