将熊猫数据框保存到Google Cloud Bucket

时间:2019-06-14 11:08:19

标签: python pandas google-cloud-platform google-cloud-storage

我想将熊猫数据框直接保存到Google云存储中。我使用write-a-pandas-dataframe-to-google-cloud-storage-or-bigquery尝试了不同的方法。但是我无法保存。

注意:我只能使用google.cloud软件包

下面是我尝试的代码

from google.cloud import storage
import pandas as pd
input_dict = [{'Name': 'A', 'Id': 100}, {'Name': 'B', 'Id': 110}, {'Name': 'C', 'Id': 120}]
df = pd.DataFrame(input_dict)

尝试:1

destination = f'gs://bucket_name/test.csv'
df.to_csv(destination)

尝试:2

storage_client = storage.Client(project='project')
bucket = storage_client.get_bucket('bucket_name')
gs_file = bucket.blob('test.csv')
df.to_csv(gs_file)

我遇到了错误

对于选项1:没有这样的文件或目录:'gs://bucket_name/test.csv'

选项2:“ Blob”对象没有属性“ close”

谢谢

Raghunath。

4 个答案:

答案 0 :(得分: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)

来源 Write a Pandas DataFrame to Google Cloud Storage or BigQuery

答案 1 :(得分:0)

在写入GCS之前将文件写入目录。

import pandas as pd
from google.cloud import storage

storage_client = storage.Client()
bucket = storage_client.get_bucket('[bucket_name]')
blob = bucket.blob('panda.csv')

input_dict = [{'Name': 'A', 'Id': 100}, {'Name': 'B', 'Id': 110}, {'Name': 'C', 'Id': 120}]
df = pd.DataFrame(input_dict)
df.to_csv('/home/[path]/panda.csv')

blob.upload_from_filename('/home/[path]/panda.csv')
print('File panda.csv uploaded')

答案 2 :(得分:0)

from google.cloud import storage
import os
from io import StringIO # if going with no saving csv file

# say where your private key to google cloud exists
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path/to/your-google-cloud-private-key.json'

df = pd.DataFrame([{'Name': 'A', 'Id': 100}, {'Name': 'B', 'Id': 110}])

首先将其写入您计算机上的csv文件并上传:

df.to_csv('local_file.csv')
gcs.get_bucket('BUCKET_NAME').blob('FILE_NAME.csv').upload_from_filename('local_file.csv', content_type='text/csv')

如果您不想创建临时的csv文件,请使用StringIO:

f = StringIO()
df.to_csv(f)
f.seek(0)
gcs.get_bucket('BUCKET_NAME').blob('FILE_NAME.csv').upload_from_file(f, content_type='text/csv')

答案 3 :(得分:-1)

这对我有用

BUCKET_NAME= "TEST-BUCKET"
storage_client = storage.Client()
bucket = storage_client.get_bucket(BUCKET_NAME)
    
fileout = "/folder1/consolidatedOutput.csv"

#convert data frame to string and write it

destination_blob = bucket.blob(file_out)
destination_blob.upload_from_string(df.to_string(index=False,justify='left'))