BigQuery DataFrame 사용

미리보기 중 지원을 받으려면 bigframes-feedback@google.com으로 이메일을 보내세요.

이 문서에서는 BigQuery DataFrame을 사용하여 BigQuery 노트북에서 데이터를 분석하고 조작하는 방법을 설명합니다.

BigQuery DataFrame은 BigQuery 노트북에서 데이터를 분석하고 머신러닝 태스크를 수행하는 데 사용할 수 있는 Python 클라이언트 라이브러리입니다.

BigQuery DataFrame은 다음 부분으로 구성됩니다.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $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 DataFrame을 사용하려면 다음 Identity and Access Management(IAM) 역할이 필요합니다.

노트북 만들기

BigQuery 편집자에서 노트북 만들기의 안내에 따라 새 노트북을 만듭니다.

BigQuery DataFrame 옵션 설정

설치 후에는 BigQuery DataFrame을 사용할 위치프로젝트를 지정해야 합니다.

다음 방법으로 노트북에서 위치와 프로젝트를 정의할 수 있습니다.

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는 BigQuery에서 데이터를 분석하고 조작하는 데 사용할 수 있는 pandas와 비슷한 API를 제공합니다. bigframes.pandas API는 테라바이트 단위의 BigQuery 데이터 처리를 지원하도록 확장 가능하며 BigQuery 쿼리 엔진을 사용하여 계산을 수행합니다.

bigframes.pandas API는 다음 기능을 제공합니다.

입력 및 출력
로컬 CSV 파일, Cloud Storage 파일, pandas DataFrame, BigQuery 모델, BigQuery 함수를 비롯한 다양한 소스에서 데이터에 액세스하여 BigQuery DataFrame에 로드할 수 있습니다. BigQuery DataFrame에서 BigQuery 테이블을 만들 수도 있습니다.
데이터 조작
개발에 SQL 대신 Python을 사용할 수 있습니다. Python에서 모든 BigQuery 데이터 조작을 개발할 수 있으므로 언어 간에 전환하고 SQL 문을 텍스트 문자열로 캡처하지 않아도 됩니다. bigframes.pandas API는 250개가 넘는 pandas 함수를 제공합니다.
Python 생태계 및 시각화
bigframes.pandas API는 전체 Python 생태계 생태계의 게이트웨이입니다. API는 고급 통계 작업을 지원하며 BigQuery DataFrame에서 생성된 집계를 시각화할 수 있습니다. 샘플링 작업이 내장된 BigQuery DataFrame에서 pandas DataFrame으로 전환할 수도 있습니다.
커스텀 Python 함수
커스텀 Python 함수 및 패키지를 사용할 수 있습니다. bigframes.pandas를 사용하면 BigQuery에서 스칼라 Python 함수를 실행하는 원격 함수를 배포할 수 있습니다. 이러한 함수를 BigQuery로 다시 SQL 루틴으로 유지하고 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 모듈을 사용하여 클러스터링 모델의 에스티메이터를 만들 수 있습니다.

다음 코드 샘플은 bigframes.ml.cluster KMeans 클래스를 사용하여 데이터 세분화를 위한 K-평균 클러스터링 모델을 만드는 방법을 보여줍니다.

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)의 에스티메이터를 만들 수 있습니다.

다음 코드 샘플은 bigframes.ml.llm PaLM2TextGenerator 클래스를 사용하여 텍스트 생성을 위한 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는 BigQuery, Cloud Functions, Vertex AI, 기타 Google Cloud 서비스를 사용하며 이는 자체 비용이 발생합니다. 일반적인 사용 중에 라이브러리는 기본적으로 7일 동안 중간 BigQuery 테이블에 데이터를 저장합니다.

다음 단계