【发布时间】:2018-07-30 21:41:29
【问题描述】:
我正在尝试使用记录在 here 的 pandas.DataFrame.to_gbq() 函数将 pandas.DataFrame 上传到 Google Big Query。问题是to_gbq() 需要 2.3 分钟,而直接上传到 Google Cloud Storage 需要不到一分钟。我打算上传一堆数据帧(~32),每个数据帧的大小都差不多,所以我想知道什么是更快的选择。
这是我正在使用的脚本:
dataframe.to_gbq('my_dataset.my_table',
'my_project_id',
chunksize=None, # I have tried with several chunk sizes, it runs faster when it's one big chunk (at least for me)
if_exists='append',
verbose=False
)
dataframe.to_csv(str(month) + '_file.csv') # the file size its 37.3 MB, this takes almost 2 seconds
# manually upload the file into GCS GUI
print(dataframe.shape)
(363364, 21)
我的问题是,什么更快?
- 使用
pandas.DataFrame.to_gbq()函数上传Dataframe - 将
Dataframe保存为 CSV,然后使用 Python API 将其作为文件上传到 BigQuery - 将
Dataframe保存为 CSV,然后使用 this procedure 将文件上传到 Google Cloud Storage,然后从 BigQuery 中读取它
更新:
备选方案 1 似乎比备选方案 2 更快,(使用 pd.DataFrame.to_csv() 和 load_data_from_file() 17.9 secs more in average with 3 loops):
def load_data_from_file(dataset_id, table_id, source_file_name):
bigquery_client = bigquery.Client()
dataset_ref = bigquery_client.dataset(dataset_id)
table_ref = dataset_ref.table(table_id)
with open(source_file_name, 'rb') as source_file:
# This example uses CSV, but you can use other formats.
# See https://cloud.google.com/bigquery/loading-data
job_config = bigquery.LoadJobConfig()
job_config.source_format = 'text/csv'
job_config.autodetect=True
job = bigquery_client.load_table_from_file(
source_file, table_ref, job_config=job_config)
job.result() # Waits for job to complete
print('Loaded {} rows into {}:{}.'.format(
job.output_rows, dataset_id, table_id))
【问题讨论】:
-
我建议你使用 pydatalab 包(你的第三种方法)。我们使用该包对 pandas 原生函数从 bigquery 下载的速度有了很大提升
-
那些时间似乎很高。您使用的是什么版本的 pandas-gbq? 0.3.0 版的上传速度应该会更快
-
@NicoAlbers 如果库之间存在实质性差异,我感到很惊讶——我发现 pandas-gbq 的速度有点快。你有例子吗?
-
我最近开了一个关于python和BQ之间性能的线程:github.com/pydata/pandas-gbq/issues/133
-
我才发现是和老版本比较的,有时间我就比较一下
标签: python pandas google-bigquery google-cloud-storage google-cloud-python