{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# BigQuery extension for pandas\n", "\n", "BigQuery DataFrames provides a pandas extension to execute BigQuery SQL scalar functions directly on pandas DataFrames." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import bigframes # This import registers the bigquery accessor." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, BigQuery DataFrames selects a location to process data based on the\n", "data location, but using a pandas object doesn't provide such informat. If\n", "processing location is important to you, configure the location before using the\n", "accessor." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import bigframes.pandas as bpd\n", "\n", "bpd.reset_session()\n", "bpd.options.bigquery.location = \"US\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using `sql_scalar`\n", "\n", "The `bigquery.sql_scalar` method allows you to apply a SQL scalar function to a pandas DataFrame by converting it to BigFrames, executing the SQL in BigQuery, and returning the result as a pandas Series." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " Query processed 0 Bytes in a moment of slot time.\n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "0 2.0\n", "1 3.0\n", "2 4.0\n", "dtype: Float64" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.DataFrame({\"a\": [1.5, 2.5, 3.5]})\n", "result = df.bigquery.sql_scalar(\"ROUND({0}, 0)\")\n", "result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also use multiple columns." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " Query processed 0 Bytes in a moment of slot time.\n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "0 11\n", "1 22\n", "2 33\n", "dtype: Int64" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.DataFrame({\"a\": [1, 2, 3], \"b\": [10, 20, 30]})\n", "result = df.bigquery.sql_scalar(\"{a} + {b}\")\n", "result" ] } ], "metadata": { "kernelspec": { "display_name": "venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.9" } }, "nbformat": 4, "nbformat_minor": 4 }