在筆記本中探索查詢結果

您可以在 BigQuery 中使用 Colab Enterprise 筆記本探索 BigQuery 查詢結果。

在本教學課程中,您將查詢 BigQuery 公開資料集中的資料,並在筆記本中探索查詢結果。

所需權限

如要建立及執行 Notebook,您需要下列 Identity and Access Management (IAM) 角色:

在筆記本中開啟查詢結果

您可以執行 SQL 查詢,然後使用筆記本探索資料。如果您想先修改 BigQuery 中的資料再進行處理,或是只需要表格中的部分欄位,這個方法就非常實用。

  1. 前往 Cloud de Confiance 控制台的「BigQuery」頁面。

    前往「BigQuery」

  2. 在「Type to search」(輸入要搜尋的字詞) 欄位中輸入 bigquery-public-data

    如果未顯示該專案,請在搜尋欄位中輸入 bigquery,然後按一下「Search to all projects」(將搜尋範圍擴及所有專案),將搜尋字串與現有專案進行比對。

  3. 依序選取「bigquery-public-data」>「ml_datasets」>「penguins」

  4. 針對「企鵝」表格,依序點選 「查看動作」和「查詢」

  5. 在產生的查詢中加入星號 (*) 以選取欄位,如下列範例所示:

    SELECT * FROM `bigquery-public-data.ml_datasets.penguins` LIMIT 1000;
  6. 按一下「執行」

  7. 在「查詢結果」部分,依序點選「開啟方式」和「Notebook」

準備使用筆記本

連線至執行階段並設定應用程式預設值,準備使用筆記本。

  1. 在筆記本標頭中,按一下「連線」,即可連線至預設執行階段
  2. 在「設定」程式碼區塊中,按一下 「執行儲存格」

探索資料

  1. 如要將 penguins 資料載入 BigQuery DataFrame 並顯示結果,請按一下「Result set loaded from BigQuery job as a DataFrame」(從 BigQuery 工作載入的結果集做為 DataFrame) 區塊中程式碼區塊的「Run cell」(執行儲存格)
  2. 如要取得資料的描述性指標,請在「Show descriptive statistics using describe()」(使用 describe() 顯示描述性統計資料) 部分的程式碼區塊中,點選「Run cell」(執行儲存格)
  3. 選用:使用其他 Python 函式或套件探索及分析資料。

下列程式碼範例顯示如何使用 bigframes.pandas 分析資料,以及如何使用 bigframes.ml 從 BigQuery DataFrame 中的 penguins 資料建立線性迴歸模型:

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)
)

# Create the Linear Regression model
from bigframes.ml.linear_model import LinearRegression

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

# Drop the columns we don't care about
adelie_data = adelie_data.drop(columns=["species"])

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

# Pick feature columns and label column
X = training_data[
    [
        "island",
        "culmen_length_mm",
        "culmen_depth_mm",
        "flipper_length_mm",
        "sex",
    ]
]
y = training_data[["body_mass_g"]]

model = LinearRegression(fit_intercept=False)
model.fit(X, y)
model.score(X, y)