簡體   English   中英

將 Pandas DataFrame 寫入 Google Cloud Storage 或 BigQuery

[英]Write a Pandas DataFrame to Google Cloud Storage or BigQuery

您好,感謝您的時間和考慮。 我正在 Google Cloud Platform/Datalab 中開發 Jupyter Notebook。 我已經創建了一個 Pandas DataFrame 並且想將此 DataFrame 寫入 Google Cloud Storage(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 文檔的各種方法,但仍然失敗。 謝謝

嘗試以下工作示例:

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)

我使用了這個例子,以及來自datalab github 站點_table.py文件作為參考。 您可以在 鏈接中找到其他datalab源代碼文件。

上傳到 Google Cloud Storage 而不寫入臨時文件,僅使用標准 GCS 模塊

from google.cloud import storage
import os
import pandas as pd

# Only need this if you're running this code locally.
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'/your_GCP_creds/credentials.json'

df = pd.DataFrame(data=[{1,2,3},{4,5,6}],columns=['a','b','c'])

client = storage.Client()
bucket = client.get_bucket('my-bucket-name')
    
bucket.blob('upload_test/test.csv').upload_from_string(df.to_csv(), 'text/csv')

使用 Google Cloud Datalab 文檔

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

將 Pandas DataFrame 寫入 BigQuery

更新@Anthonios Partheniou 的回答。
現在的代碼有點不同 - 截至2017 年 11 月 29 日

定義 BigQuery 數據集

將包含project_iddataset_id的元組dataset_idbq.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)

自 2017 年以來,Pandas 有一個 Dataframe 到 BigQuery 函數pandas.DataFrame.to_gbq

文檔有一個示例:

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

參數if_exists可以設置為 'fail'、'replace' 或 'append'

另請參閱此示例

我花了很多時間找到最簡單的方法來解決這個問題:

import pandas as pd

df = pd.DataFrame(...)

df.to_csv('gs://bucket/path')

對於使用Dask的任務,我有一個更簡單的解決方案。 您可以將 DataFrame 轉換為 Dask DataFrame,后者可以寫入 Cloud Storage 上的 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})  

我認為你需要將它加載到一個普通的字節變量中,並在一個單獨的單元格中使用 %%storage write --variable $sample_bucketpath(see the doc) ......我仍在弄清楚......但這大致與讀取 CSV 文件所需要做的相反,我不知道它是否對寫入有影響,但我必須使用 BytesIO 來讀取由 %% storage read 命令創建的緩沖區......希望它幫助,讓我知道!

Google storage

def write_df_to_gs(df, gs_key):
    df.to_csv(gs_key)    

BigQuery

def upload_df_to_bq(df, project, bq_table):
    df.to_gbq(bq_table, project_id=project, if_exists='replace')

要使用身份驗證到期服務帳戶在 GCS 中保存鑲木地板文件:

df.to_parquet("gs://<bucket-name>/file.parquet",
               storage_options={"token": <path-to-gcs-service-account-file>}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM