【问题标题】:Upload Pandas data frame from local machine to Google Cloud bucket将 Pandas 数据帧从本地机器上传到 Google Cloud 存储桶
【发布时间】:2019-10-29 00:27:38
【问题描述】:

我想将本地机器上的 pandas 数据帧直接上传到 Google Cloud Storage,因此,我不在 Cloud Function 中。我尝试了使用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”对象没有“关闭”属性

谢谢,

拉古纳特。

【问题讨论】:

  • 我尝试了类似的设置,它对我有用。你的 Python 代码在 GCP 中吗? Cloud Storage 存储分区是否已经创建?您的 try1 解决方案应该可以通过 Cloud Shell 运行。
  • 嗨,Raghunath 你能找到答案吗?我遇到了完全相同的问题,我正在编写一个 python 脚本,该脚本将由将 df 写入 CSV 并将其保存在 GCS 存储桶中的气流触发,但我得到了缺少可选依赖项“gcsfs”。处理GCS文件需要gcsfs库使用pip或conda安装gcsfs。
  • 目前这个需求没有解决方案。我已经开发了代码来创建临时文件,然后上传到 GS

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


【解决方案1】:
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')

【讨论】:

  • 谢谢 :) ........ 我只想添加:gcs = storage.Client() 而不是 gcs.get_bucket..,只需使用:gcs.bucket
【解决方案2】:

在写入 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')

【讨论】:

  • 我需要直接的方法而不是使用临时文件(我知道临时文件的方法)
【解决方案3】:

也许这篇文章可以帮助你

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

【讨论】:

    【解决方案4】:

    这对我有用

    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'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 2019-06-21
      • 2021-03-20
      • 2018-06-18
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      相关资源
      最近更新 更多