BigQuery DataFrames を使用してデータを操作する

このドキュメントでは、BigQuery DataFrames で使用できるデータ操作機能について説明します。bigframes.bigquery ライブラリに記載されている関数を確認できます。

必要なロール

このドキュメントのタスクを実行するために必要な権限を取得するには、プロジェクトに対して次の IAM ロールを付与するように管理者へ依頼してください。

ロールの付与については、プロジェクト、フォルダ、組織へのアクセスを管理するをご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

ノートブック、Python REPL、コマンドラインなどのインタラクティブ環境でエンドユーザー認証を実行する場合は、必要に応じて BigQuery DataFrames が認証を要求します。実行しない場合は、さまざまな環境でアプリケーションのデフォルト認証情報を設定する方法をご覧ください。

pandas API

BigQuery DataFrames の注目すべき特徴は、bigframes.pandas API が pandas ライブラリの API と同様に設計されていることです。この設計により、データ操作タスクに使い慣れた構文パターンを使用できます。BigQuery DataFrames API を介して定義されたオペレーションはサーバーサイドで実行され、BigQuery 内に保存されたデータを直接操作するため、データセットを BigQuery から転送する必要がなくなります。

BigQuery DataFrames でサポートされている pandas API を確認するには、サポートされている pandas API をご覧ください。

データの検査と操作

bigframes.pandas API を使用して、データの検査と計算のオペレーションを実行できます。次のコードサンプルでは、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)
)

BigQuery ライブラリ

BigQuery ライブラリには、pandas に相当するものが存在しない BigQuery SQL 関数が用意されています。以降のセクションでは、いくつかの例を紹介します。

配列値を処理する

bigframes.bigquery ライブラリの bigframes.bigquery.array_agg() 関数を使用すると、groupby オペレーションの後に値を集計できます。

import bigframes.bigquery as bbq
import bigframes.pandas as bpd

s = bpd.Series([0, 1, 2, 3, 4, 5])

# Group values by whether they are divisble by 2 and aggregate them into arrays
bbq.array_agg(s.groupby(s % 2 == 0))
# False    [1 3 5]
# True     [0 2 4]
# dtype: list<item: int64>[pyarrow]

array_length()array_to_string() の配列関数も使用できます。

構造体 Series オブジェクトを作成する

bigframes.bigquery ライブラリの bigframes.bigquery.struct() 関数を使用して、DataFrame 内の各列のサブフィールドを含む新しい構造体 Series オブジェクトを作成できます。

import bigframes.bigquery as bbq
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 a new STRUCT Series with subfields for each column in a DataFrames.
lengths = bbq.struct(
    bq_df[["culmen_length_mm", "culmen_depth_mm", "flipper_length_mm"]]
)

lengths.peek()
# 146	{'culmen_length_mm': 51.1, 'culmen_depth_mm': ...
# 278	{'culmen_length_mm': 48.2, 'culmen_depth_mm': ...
# 337	{'culmen_length_mm': 36.4, 'culmen_depth_mm': ...
# 154	{'culmen_length_mm': 46.5, 'culmen_depth_mm': ...
# 185	{'culmen_length_mm': 50.1, 'culmen_depth_mm': ...
# dtype: struct[pyarrow]

タイムスタンプを Unix エポックに変換する

bigframes.bigquery ライブラリの bigframes.bigquery.unix_micros() 関数を使用して、タイムスタンプを Unix マイクロ秒に変換できます。

import pandas as pd

import bigframes.bigquery as bbq
import bigframes.pandas as bpd

# Create a series that consists of three timestamps: [1970-01-01, 1970-01-02, 1970-01-03]
s = bpd.Series(pd.date_range("1970-01-01", periods=3, freq="d", tz="UTC"))

bbq.unix_micros(s)
# 0               0
# 1     86400000000
# 2    172800000000
# dtype: Int64

unix_seconds()unix_millis() の時間関数を使用することも可能です。

SQL スカラー関数を使用する

bigframes.bigquery ライブラリの bigframes.bigquery.sql_scalar() 関数を使用して、単一列の式を表す任意の SQL 構文にアクセスできます。

import bigframes.bigquery as bbq
import bigframes.pandas as bpd

# Load data from BigQuery
query_or_table = "bigquery-public-data.ml_datasets.penguins"

# The sql_scalar function can be used to inject SQL syntax that is not supported
# or difficult to express with the bigframes.pandas APIs.
bq_df = bpd.read_gbq(query_or_table)
shortest = bbq.sql_scalar(
    "LEAST({0}, {1}, {2})",
    columns=[
        bq_df["culmen_depth_mm"],
        bq_df["culmen_length_mm"],
        bq_df["flipper_length_mm"],
    ],
)

shortest.peek()
#         0
# 149	18.9
# 33	16.3
# 296	17.2
# 287	17.0
# 307	15.0
# dtype: Float64

次のステップ