【问题标题】:How can I upload a Pandas dataframe directly to BigQuery?如何将 Pandas 数据框直接上传到 BigQuery?
【发布时间】:2021-02-16 14:54:43
【问题描述】:
我一直在使用 Pandas 格式化数据帧,然后我将其转换为 CSV,然后手动上传到 BigQuery(取决于大小,我之前上传到 Cloud Storage)。
我经常使用 Google Colaboratory 作为我的笔记本 UI。
是否可以通过直接从 Pandas 上传到 BQ/CS 来简化流程?怎么样?
【问题讨论】:
标签:
pandas
google-cloud-platform
google-bigquery
google-cloud-storage
google-colaboratory
【解决方案1】:
您可以利用to_gbq
df = pandas.DataFrame(
{
"my_string": ["a", "b", "c"],
"my_int64": [1, 2, 3],
"my_float64": [4.0, 5.0, 6.0],
"my_bool1": [True, False, True],
"my_bool2": [False, True, False],
"my_dates": pandas.date_range("now", periods=3),
}
)
pandas_gbq.to_gbq(df, destination_id = 'dataset.table', project_id='project_id')
【解决方案2】:
您可以使用load_table_from_dataframe 将数据从 Pandas 加载到 BigQuery:
bigqueryClient = bigquery.Client()
tableRef = bigqueryClient.dataset("bq-dataset").table("bq-table")
bigqueryJob = bigqueryClient.load_table_from_dataframe(dataFrame, tableRef)
bigqueryJob.result()
【解决方案3】:
定义 BigQuery 数据集
将包含 project_id 和 dataset_id 的元组传递给 bq.Dataset。
# define a BigQuery dataset
bigquery_dataset_name = ('project_id', 'dataset_id')
dataset = bq.Dataset(name = bigquery_dataset_name)
定义 BigQuery 表
将包含 project_id、dataset_id 和表名的元组传递给 bq.Table。
# define a BigQuery table
bigquery_table_name = ('project_id', 'dataset_id', 'table_name')
table = bq.Table(bigquery_table_name)
创建数据集/表并写入BQ中的表
# Create BigQuery dataset
if not dataset.exists():
dataset.create()
# Create or overwrite the existing table if it exists
table_schema = bq.Schema.from_data(dataFrame_name)
table.create(schema = table_schema, overwrite = True)
# Write the DataFrame to a BigQuery table
table.insert(dataFrame_name)