Run a query with pandas-gbq

Use the pandas-gbq package to run a simple query.

Code sample

Python

Before trying this sample, follow the Python setup instructions in the BigQuery quickstart using client libraries. For more information, see the BigQuery Python API reference documentation.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

import bigframes.pandas as bpd
import pandas as pd
import pandas_gbq

# Set partial ordering mode for BigQuery DataFrames.
bpd.options.bigquery.ordering_mode = "partial"


def read_gbq_simple_pandas_gbq() -> pd.DataFrame:
    """Queries BigQuery using pandas-gbq and returns an in-memory DataFrame."""
    sql = """
    SELECT name, SUM(number) as total_people
    FROM `bigquery-public-data.usa_names.usa_1910_2013`
    WHERE state = 'TX'
    GROUP BY name
    ORDER BY total_people DESC
    LIMIT 20
    """
    df_pandas = pandas_gbq.read_gbq(sql)
    print("Queried using pandas-gbq.")
    return df_pandas


def read_gbq_simple_bigframes() -> bpd.DataFrame:
    """Queries BigQuery using BigQuery DataFrames and returns a distributed DataFrame."""
    sql = """
    SELECT name, SUM(number) as total_people
    FROM `bigquery-public-data.usa_names.usa_1910_2013`
    WHERE state = 'TX'
    GROUP BY name
    ORDER BY total_people DESC
    LIMIT 20
    """
    df_bigframes = bpd.read_gbq(sql)
    print("Queried using BigQuery DataFrames.")
    return df_bigframes


# [Preferred] Run using pandas-gbq:
# df_pandas = read_gbq_simple_pandas_gbq()
# print(df_pandas.head())

# Alternatively, run using BigQuery DataFrames:
# df_bigframes = read_gbq_simple_bigframes()
# print(df_bigframes.head())

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.