이 문서에서는 BigQuery DataFrame을 사용할 때 세션을 관리하고 입력 및 출력 (I/O) 작업을 실행하는 방법을 설명합니다. 세션을 만들고 사용하는 방법, 인메모리 데이터로 작업하는 방법, 파일 및 BigQuery 테이블에서 읽고 쓰는 방법을 알아봅니다.
BigQuery 세션
BigQuery DataFrames는 메타데이터를 관리하기 위해 내부적으로 로컬 세션 객체를 사용합니다. 각 DataFrame 및 Series 객체는 세션에 연결되고, 각 세션은 위치에 연결되며, 세션의 각 쿼리는 세션을 만든 위치에서 실행됩니다. 다음 코드 샘플을 사용하여 세션을 수동으로 만들고 데이터를 로드하는 데 사용합니다.
importbigframesimportbigframes.pandasasbpd# Create session objectcontext=bigframes.BigQueryOptions(project=YOUR_PROJECT_ID,location=YOUR_LOCATION,)session=bigframes.Session(context)# Load a BigQuery table into a dataframedf1=session.read_gbq("bigquery-public-data.ml_datasets.penguins")# Create a dataframe with local data:df2=bpd.DataFrame({"my_col":[1,2,3]},session=session)
동일한 설정으로 초기화하더라도 여러 세션 인스턴스의 데이터를 결합할 수는 없습니다. 다음 코드 샘플은 서로 다른 세션 인스턴스의 데이터를 결합하려고 하면 오류가 발생하는 것을 보여줍니다.
importbigframesimportbigframes.pandasasbpdcontext=bigframes.BigQueryOptions(location=YOUR_LOCATION,project=YOUR_PROJECT_ID)session1=bigframes.Session(context)session2=bigframes.Session(context)series1=bpd.Series([1,2,3,4,5],session=session1)series2=bpd.Series([1,2,3,4,5],session=session2)try:series1+series2exceptValueErrorase:print(e)# Error message: Cannot use combine sources from multiple sessions
전역 세션
BigQuery DataFrames는 bigframes.pandas.get_global_session() 메서드로 액세스할 수 있는 기본 전역 세션을 제공합니다. Colab에서는 bigframes.pandas.options.bigquery.project 속성을 사용하기 전에 프로젝트 ID를 제공해야 합니다. bigframes.pandas.options.bigquery.location 속성으로 위치를 설정할 수도 있습니다. 이 속성은 기본적으로 US 멀티 리전으로 설정됩니다.
다음 코드 샘플은 전역 세션의 옵션을 설정하는 방법을 보여줍니다.
importbigframes.pandasasbpd# Set project ID for the global sessionbpd.options.bigquery.project=YOUR_PROJECT_ID# Update the global default session locationbpd.options.bigquery.location=YOUR_LOCATION
전역 세션의 위치 또는 프로젝트를 재설정하려면 bigframes.pandas.close_session() 메서드를 실행하여 현재 세션을 닫습니다.
많은 BigQuery DataFrames 기본 제공 함수는 기본적으로 전역 세션을 사용합니다. 다음 코드 샘플은 기본 제공 함수가 전역 세션을 사용하는 방법을 보여줍니다.
# The following two statements are essentially the samedf=bpd.read_gbq("bigquery-public-data.ml_datasets.penguins")df=bpd.get_global_session().read_gbq("bigquery-public-data.ml_datasets.penguins")
인메모리 데이터
pandas로 객체를 만드는 것과 마찬가지로 내장 Python 또는 NumPy 데이터 구조를 사용하여 Dataframes 및 Series 객체를 만들 수 있습니다. 다음 코드 샘플을 사용하여 객체를 만듭니다.
importnumpyasnpimportbigframes.pandasasbpds=bpd.Series([1,2,3])# Create a dataframe with Python dictdf=bpd.DataFrame({"col_1":[1,2,3],"col_2":[4,5,6],})# Create a series with Numpys=bpd.Series(np.arange(10))
read_pandas() 메서드 또는 생성자를 사용하여 pandas 객체를 DataFrames 객체로 변환하려면 다음 코드 샘플을 사용하세요.
importnumpyasnpimportpandasaspdimportbigframes.pandasasbpdpd_df=pd.DataFrame(np.random.randn(4,2))# Convert Pandas dataframe to BigQuery DataFrame with read_pandas()df_1=bpd.read_pandas(pd_df)# Convert Pandas dataframe to BigQuery DataFrame with the dataframe constructordf_2=bpd.DataFrame(pd_df)
to_pandas() 메서드를 사용하여 BigQuery DataFrames 데이터를 메모리에 로드하려면 다음 코드 샘플을 사용하세요.
importbigframes.pandasasbpdbf_df=bpd.DataFrame({"my_col":[1,2,3]})# Returns a Pandas Dataframebf_df.to_pandas()bf_s=bpd.Series([1,2,3])# Returns a Pandas Seriesbf_s.to_pandas()
dry_run 매개변수를 사용한 비용 추정
대량의 데이터를 로드하는 데는 많은 시간과 리소스가 필요할 수 있습니다. 처리되는 데이터의 양을 확인하려면 to_pandas() 호출에서 dry_run=True 매개변수를 사용하세요. 다음 코드 샘플을 사용하여 시험 이전을 실행합니다.
importbigframes.pandasasbpddf=bpd.read_gbq("bigquery-public-data.ml_datasets.penguins")# Returns a Pandas series with dry run statsdf.to_pandas(dry_run=True)
파일 읽기 및 쓰기
호환되는 파일에서 BigQuery DataFrames로 데이터를 읽을 수 있습니다. 이러한 파일은 로컬 머신 또는 Cloud Storage에 있을 수 있습니다. 다음 코드 샘플을 사용하여 CSV 파일에서 데이터를 읽습니다.
importbigframes.pandasasbpd# Read a CSV file from GCSdf=bpd.read_csv("gs://cloud-samples-data/bigquery/us-states/us-states.csv")
to_csv 메서드를 사용하여 BigQuery DataFrames를 로컬 파일 또는 Cloud Storage 파일에 저장하려면 다음 코드 샘플을 사용하세요.
importbigframes.pandasasbpddf=bpd.DataFrame({"my_col":[1,2,3]})# Write a dataframe to a CSV file in GCSdf.to_csv(f"gs://{YOUR_BUCKET}/myfile*.csv")
BigQuery 테이블 읽기 및 쓰기
BigQuery 테이블 참조와 bigframes.pandas.read_gbq 함수를 사용하여 BigQuery DataFrames를 만들려면 다음 코드 샘플을 사용하세요.
read_gbq() 함수와 함께 SQL 문자열을 사용하여 BigQuery DataFrames에 데이터를 읽어오려면 다음 코드 샘플을 사용하세요.
importbigframes.pandasasbpdsql="""SELECT species, island, body_mass_gFROM bigquery-public-data.ml_datasets.penguinsWHERE sex = 'MALE'"""df=bpd.read_gbq(sql)
DataFrame 객체를 BigQuery 테이블에 저장하려면 DataFrame 객체의 to_gbq() 메서드를 사용합니다. 다음 코드 샘플은 이를 수행하는 방법을 보여줍니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[],[],null,["# Manage BigQuery DataFrames sessions and I/O\n===========================================\n\nThis document explains how to manage sessions and perform input and output (I/O)\noperations when you use BigQuery DataFrames. You will learn how to create and\nuse sessions, work with in-memory data, and read from and write to files and\nBigQuery tables.\n\nBigQuery sessions\n-----------------\n\nBigQuery DataFrames uses a local session object internally to manage\nmetadata. Each `DataFrame` and `Series` object connects to a session, each\nsession connects to a [location](/bigquery/docs/locations), and each query in a\nsession runs in the location where you created the session. Use the following\ncode sample to manually create a session and use it for loading data: \n\n import https://cloud.google.com/python/docs/reference/bigframes/latest/\n import bigframes.pandas as bpd\n\n # Create session object\n context = https://cloud.google.com/python/docs/reference/bigframes/latest/.https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes._config.bigquery_options.BigQueryOptions.html(\n project=YOUR_PROJECT_ID,\n location=YOUR_LOCATION,\n )\n session = https://cloud.google.com/python/docs/reference/bigframes/latest/.Session(context)\n\n # Load a BigQuery table into a dataframe\n df1 = https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.operations.blob.BlobAccessor.html#bigframes_operations_blob_BlobAccessor_session.https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.pandas.html(\"bigquery-public-data.ml_datasets.penguins\")\n\n # Create a dataframe with local data:\n df2 = bpd.DataFrame({\"my_col\": [1, 2, 3]}, session=session)\n\nYou can't combine data from multiple session instances, even if you initialize\nthem with the same settings. The following code sample shows that trying to\ncombine data from different session instances causes an error: \n\n import https://cloud.google.com/python/docs/reference/bigframes/latest/\n import bigframes.pandas as bpd\n\n context = https://cloud.google.com/python/docs/reference/bigframes/latest/.https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes._config.bigquery_options.BigQueryOptions.html(location=YOUR_LOCATION, project=YOUR_PROJECT_ID)\n\n session1 = https://cloud.google.com/python/docs/reference/bigframes/latest/.Session(context)\n session2 = https://cloud.google.com/python/docs/reference/bigframes/latest/.Session(context)\n\n series1 = bpd.Series([1, 2, 3, 4, 5], session=session1)\n series2 = bpd.Series([1, 2, 3, 4, 5], session=session2)\n\n try:\n series1 + series2\n except ValueError as e:\n print(e) # Error message: Cannot use combine sources from multiple sessions\n\n### Global session\n\nBigQuery DataFrames provides a default global session that you can\naccess with the `bigframes.pandas.get_global_session()` method. In\nColab, you must provide a project ID for the\n`bigframes.pandas.options.bigquery.project` attribute before you use it. You\ncan also set a location with the\n`bigframes.pandas.options.bigquery.location` attribute, which defaults to\nthe `US` multi-region.\n\nThe following code sample shows how to set options for the global session: \n\n import bigframes.pandas as bpd\n\n # Set project ID for the global session\n bpd.options.bigquery.project = YOUR_PROJECT_ID\n # Update the global default session location\n bpd.options.bigquery.location = YOUR_LOCATION\n\nTo reset the global session's location or project, close the current session by\nrunning the `bigframes.pandas.close_session()` method.\n\nMany BigQuery DataFrames built-in functions use the global session by\ndefault. The following code sample shows how built-in functions use the global\nsession: \n\n # The following two statements are essentially the same\n df = bpd.read_gbq(\"bigquery-public-data.ml_datasets.penguins\")\n df = bpd.get_global_session().read_gbq(\"bigquery-public-data.ml_datasets.penguins\")\n\nIn-memory data\n--------------\n\nYou can create `Dataframes` and `Series` objects with built-in Python or NumPy\ndata structures, similar to how you create objects with pandas. Use the\nfollowing code sample to create an object: \n\n import numpy as np\n\n import bigframes.pandas as bpd\n\n s = bpd.Series([1, 2, 3])\n\n # Create a dataframe with Python dict\n df = bpd.DataFrame(\n {\n \"col_1\": [1, 2, 3],\n \"col_2\": [4, 5, 6],\n }\n )\n\n # Create a series with Numpy\n s = bpd.Series(np.arange(10))\n\nTo convert `pandas` objects to `DataFrames` objects using the `read_pandas()`\nmethod or constructors, use the following code sample: \n\n import numpy as np\n import pandas as pd\n\n import bigframes.pandas as bpd\n\n pd_df = pd.DataFrame(np.random.randn(4, 2))\n\n # Convert Pandas dataframe to BigQuery DataFrame with read_pandas()\n df_1 = bpd.read_pandas(pd_df)\n # Convert Pandas dataframe to BigQuery DataFrame with the dataframe constructor\n df_2 = bpd.DataFrame(pd_df)\n\nTo use the `to_pandas()` method to load BigQuery DataFrames data into\nyour memory, use the following code sample: \n\n import bigframes.pandas as bpd\n\n bf_df = bpd.DataFrame({\"my_col\": [1, 2, 3]})\n # Returns a Pandas Dataframe\n bf_df.to_pandas()\n\n bf_s = bpd.Series([1, 2, 3])\n # Returns a Pandas Series\n bf_s.to_pandas()\n\n### Cost estimation with the `dry_run` parameter\n\nLoading a large amount of data can take a lot of time and resources. To see how\nmuch data is being processed, use the `dry_run=True` parameter in the\n`to_pandas()` call. Use the following code sample to perform a dry run: \n\n import bigframes.pandas as bpd\n\n df = bpd.read_gbq(\"bigquery-public-data.ml_datasets.penguins\")\n\n # Returns a Pandas series with dry run stats\n df.to_pandas(dry_run=True)\n\nRead and write files\n--------------------\n\nYou can read data from compatible files into a BigQuery DataFrames. These\nfiles can be on your local machine or in Cloud Storage. Use the following code\nsample to read data from a CSV file: \n\n import bigframes.pandas as bpd\n\n # Read a CSV file from GCS\n df = bpd.read_csv(\"gs://cloud-samples-data/bigquery/us-states/us-states.csv\")\n\nTo save your BigQuery DataFrames to local files or Cloud Storage files\nusing the `to_csv` method, use the following code sample: \n\n import bigframes.pandas as bpd\n\n df = bpd.DataFrame({\"my_col\": [1, 2, 3]})\n # Write a dataframe to a CSV file in GCS\n df.to_csv(f\"gs://{YOUR_BUCKET}/myfile*.csv\")\n\nRead and write BigQuery tables\n------------------------------\n\nTo create BigQuery DataFrames using BigQuery table\nreferences and the `bigframes.pandas.read_gbq` function, use the following code\nsample: \n\n import bigframes.pandas as bpd\n\n df = bpd.read_gbq(\"bigquery-public-data.ml_datasets.penguins\")\n\nTo use a SQL string with the `read_gbq()` function to read data into\nBigQuery DataFrames, use the following code sample: \n\n import bigframes.pandas as bpd\n\n sql = \"\"\"\n SELECT species, island, body_mass_g\n FROM bigquery-public-data.ml_datasets.penguins\n WHERE sex = 'MALE'\n \"\"\"\n\n df = bpd.read_gbq(sql)\n\n| **Note:** If you specify a table when calling the `read_gbq()`, `read_gbq_table()`, or `read_gbq_query()` function, and you haven't set the `bigframes.pandas.options.bigquery.location` attribute before the function call, then BigQuery DataFrames automatically sets the `bigframes.pandas.options.bigquery.location` attribute to the table's location. For information on how to manually specify the location, see [Global session](#global-session).\n\nTo save your `DataFrame` object to a BigQuery table, use the\n`to_gbq()` method of your `DataFrame` object. The following code sample shows\nhow to do that: \n\n import bigframes.pandas as bpd\n\n df = bpd.DataFrame({\"my_col\": [1, 2, 3]})\n\n df.to_gbq(f\"{YOUR_PROJECT_ID}.{YOUR_DATASET_ID}.{YOUR_TABLE_NAME}\")\n\nWhat's next\n-----------\n\n- Learn how to [use BigQuery DataFrames](/bigquery/docs/use-bigquery-dataframes).\n- Learn how to [work with data types in BigQuery DataFrames](/bigquery/docs/bigquery-dataframes-datatypes).\n- Learn how to [visualize graphs using BigQuery DataFrames](/bigquery/docs/dataframes-visualizations).\n- Explore the [BigQuery DataFrames API reference](/python/docs/reference/bigframes/latest/summary_overview)."]]