bigquery的python工具
bqtools的Python项目详细描述
bigquery的python工具
为什么?
对于数据收集和数据探索,我们喜欢使用BigQuery。但是我们还没有找到一个python库来轻松地处理重复的任务,比如添加新数据(可能不一致的模式)和模式迁移。因此,我们为这些任务采取了一些解决方案,并将它们放入这个库中。
什么?
bqtools
为使用python原生类型(不同于pandas dtype)和
一些方便的类型检查、推理和转换。由bqtools
创建的表对象可以从bigquery读取、存储在本地、从本地文件读取并写入bigquery。表架构可以更改,数据可以添加或修改。
安装
pip install --upgrade bqtools
示例:
创建基本表
fromfourtytwoimportbqtoolsschema=[{'name':'number','field_type':'INTEGER'},{'name':'text','field_type':'STRING'},]# valid BigQuery types see: # https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types# geo, struct and array are currently not/not fully supported# data = columns of liststable=bqtools.BQTable(schema=schema,data=[[1,2,3,4],['a','b','c','d']])# data = rows of dictstable=bqtools.BQTable(schema=schema,data=[{'number':1,'text':'a'},{'number':2,'text':'b'},...])
查看数据
print(table.data)# list of all columnsprint(table.rows(n=10))# list of first n rows# convert to pandas.DataFramedf=table.to_df()# warning: pandas dtypes may be inconsistent # with BigQuery Schema field_types
附加数据
rows=[{'number':5,'text':'e'}]table.append(rows)row=[[6,'f']]table.append(rows)
从bigquery加载表
# requires environment variable GOOGLE_APPLICATION_CREDENTIALS # or parameter credentials='path-to-credentials.json'table=bqtools.read_bq(table_ref='project_id.dataset_id.new_table_id',limit=10,# limit query rowsschema_only=False# set True to only add data)
修改表架构
# change column order and field_typenew_schema=[{'name':'text','field_type':'STRING'},{'name':'number','field_type':'FLOAT'},]table.schema(new_schema)# change column namestable.rename(columns={'number':'decimal'})
将表写入bigquery
# requires environment variable GOOGLE_APPLICATION_CREDENTIALS# or parameter credentials='path-to-credentials.json'table.to_bq(table_ref,mode='append')
本地持久化表
# write to local file (compressed binary format)table.save('local_table.bqt')# load from local filetable=bqtools.load('local_table.bqt')