首页 文章

将Pandas DataFrame写入Google Cloud Storage或BigQuery

提问于
浏览
16

您好,感谢您的时间和考虑 . 我正在Google Cloud Platform / Datalab中开发一个Jupyter笔记本 . 我创建了一个Pandas DataFrame,并希望将此DataFrame写入Google Cloud 端存储(GCS)和/或BigQuery . 我在GCS中有一个存储桶,并通过以下代码创建了以下对象:

import gcp
import gcp.storage as storage
project = gcp.Context.default().project_id    
bucket_name = 'steve-temp'           
bucket_path  = bucket_name   
bucket = storage.Bucket(bucket_path)
bucket.exists()

我尝试过基于Google Datalab文档的各种方法,但仍然失败 . 谢谢

6 回答

  • 0

    尝试以下工作示例:

    from datalab.context import Context
    import google.datalab.storage as storage
    import google.datalab.bigquery as bq
    import pandas as pd
    
    # Dataframe to write
    simple_dataframe = pd.DataFrame(data=[{1,2,3},{4,5,6}],columns=['a','b','c'])
    
    sample_bucket_name = Context.default().project_id + '-datalab-example'
    sample_bucket_path = 'gs://' + sample_bucket_name
    sample_bucket_object = sample_bucket_path + '/Hello.txt'
    bigquery_dataset_name = 'TestDataSet'
    bigquery_table_name = 'TestTable'
    
    # Define storage bucket
    sample_bucket = storage.Bucket(sample_bucket_name)
    
    # Create storage bucket if it does not exist
    if not sample_bucket.exists():
        sample_bucket.create()
    
    # Define BigQuery dataset and table
    dataset = bq.Dataset(bigquery_dataset_name)
    table = bq.Table(bigquery_dataset_name + '.' + bigquery_table_name)
    
    # Create BigQuery dataset
    if not dataset.exists():
        dataset.create()
    
    # Create or overwrite the existing table if it exists
    table_schema = bq.Schema.from_data(simple_dataframe)
    table.create(schema = table_schema, overwrite = True)
    
    # Write the DataFrame to GCS (Google Cloud Storage)
    %storage write --variable simple_dataframe --object $sample_bucket_object
    
    # Write the DataFrame to a BigQuery table
    table.insert(simple_dataframe)
    

    我使用this示例,并使用datalab github site中的_table.py文件作为参考 . 您可以在this链接找到其他 datalab 源代码文件 .

  • 0

    使用Google Cloud Datalab documentation

    import datalab.storage as gcs
    gcs.Bucket('bucket-name').item('to/data.csv').write_to(simple_dataframe.to_csv(),'text/csv')
    
  • 7

    将Pandas DataFrame写入BigQuery

    Update 关于@Anthonios Partheniou的回答 .
    代码现在有点不同 - 截至 Nov. 29 2017

    定义BigQuery数据集

    将包含 project_iddataset_id 的元组传递给 bq.Dataset .

    # define a BigQuery dataset    
    bigquery_dataset_name = ('project_id', 'dataset_id')
    dataset = bq.Dataset(name = bigquery_dataset_name)
    

    定义BigQuery表

    将包含 project_iddataset_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)
    
  • 11

    对于使用 Dask 的任务,我有一个更简单的解决方案 . 您可以将DataFrame转换为Dask DataFrame,可以将其写入 Cloud 存储上的csv

    import dask.dataframe as dd
    import pandas
    df # your Pandas DataFrame
    ddf = dd.from_pandas(df,npartitions=1, sort=True)
    dd.to_csv('gs://YOUR_BUCKET/ddf-*.csv', index=False, sep=',', header=False,  
                                   storage_options={'token': gcs.session.credentials})
    
  • 11

    我认为你需要将它加载到一个普通的字节变量中,并在一个单独的单元格中使用%%存储写 - 变量$ sample_bucketpath(参见doc)......我还在想出来......但这大致是我需要做的就是读取CSV文件,我不知道它是否会对写入产生影响,但我不得不使用BytesIO来读取%% storage read命令创建的缓冲区...希望它帮助,让我知道!

  • 2

    自2017年以来,Pandas拥有一个Dataframe to BigQuery功能pandas.DataFrame.to_gbq

    documentation有一个例子:

    import pandas_gbq as gbq gbq.to_gbq(df, 'my_dataset.my_table', projectid, if_exists='fail')

    参数 if_exists 可以设置为'fail','replace'或'append'

    另见example .

相关问题