【问题标题】:How to upload a dataframe to Google Cloud Storage(bucket) on Python 3?如何在 Python 3 上将数据帧上传到 Google Cloud Storage(bucket)?
【发布时间】:2020-12-25 19:29:23
【问题描述】:

我想创建一个云函数(应在每天 01:00 执行)。 函数应该

  1. 生成数据框
  2. [导出为 dataframe.csv]
  3. 将数据帧(或 .csv)推送到存储桶

.....

  • 问题1:是否可以将数据帧推送到存储桶?
  • 问题 2:如何在 CloudFunction(CF) 中创建一个 .csv 文件,以便将其推送到存储桶中?

现在更新代码:(仍然报错)

def push_cars( data ):    ##  <<----- not sure how many paramter &why??

    import requests
    import pandas as pd
    import os
    from datetime import datetime

    from google.cloud.storage.blob import Blob
    from google.cloud import storage
    #import csv               # <<--- not sure if required???


    cars_dict = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

    cars = pd.DataFrame(cars_dict, columns = ['Brand', 'Price'])

    timestamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S")
    name = "cars_" + timestamp + ".csv"

    cars.to_csv(  "/tmp/test.csv" ,index=False)
    with open('/tmp/test.csv', "w") as csv: 
      csv.write(name) 

    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "My-project.json"

    target_bucket = 'cars:python_gogo'


    storage_client = storage.Client()
    bucket         = storage_client.get_bucket(  target_bucket )
    data           = bucket        .blob(        name_output   )


对于云上的复制,您需要创建一个包含以下内容的 requirements.txt:

requests
pandas
google-cloud-storage
datetime

在云外壳中,我使用以下方法部署此 CF: gcloud 函数部署 push_cars--entry-point=push_cars--runtime=python37 --memory=1024MB --region=us-east1 --allow-unauthenticated --trigger-http

【问题讨论】:

  • 你不能只推送一个数据框。得先序列化。
  • 有解决办法吗?我可以将数据框导出为 .csv。并将这个 .csv 推送到存储桶中?

标签: python google-cloud-functions google-cloud-storage


【解决方案1】:

问题一:

dataframe不能直接写入Cloud Storage,需要是一个文件(可以是你提到的.csv),然后你可以将文件写入Google Cloud Storage存储桶。 这意味着需要第 2 步。

问题 2:

dataframe.csv 保存在/tmp 中后,您可以将其转移到Google Cloud Storage buket。

实现这两件事的代码将是这样的:

def push_cars( data, context ):

    import requests
    import pandas as pd
    import os
    from datetime import datetime

    from google.cloud.storage.blob import Blob
    from google.cloud import storage


    cars_dict = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

    cars = pd.DataFrame(cars_dict, columns = ['Brand', 'Price'])

    timestamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S")
    name = "cars_" + timestamp + ".csv"

    cars.to_csv(  cars ,index=False)
    with open('/tmp/test.csv', "w") as csv: 
      csv.write(cars) 

    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "My-project.json"

    target_bucket = 'sp500_python_gogo'

    storage_client = storage.Client()
    bucket         = storage_client.get_bucket(  target_bucket )
    with open('/tmp/test.csv', 'r') as file_obj:
      upload_blob(target_bucket, file_obj, name)

【讨论】:

  • 刚刚尝试过这种方法,但仍然无法正常工作。 1.我不确定,是否可以在这种环境中保存 .csv 文件。还得到错误代码:“错误:函数终止。推荐操作:检查日志以了解终止原因。其他故障排除文档可在 cloud.google.com/functions/docs/troubleshooting#logging 找到详细信息:[Errno 30] 只读文件系统:'test.csv'”2。我不确定是否需要导入csv包
  • 3.我不确定,如果使用 gcloud 功能进行部署是否正确:“gcloud functions deploy [name]--entry-point=[name]--runtime=python37 --memory=1024MB --region=us-east1 - -allow-unauthenticated --trigger-http" 4. 我不确定,这个函数真正需要多少参数! def push_cars(数据)?
【解决方案2】:

使用df.to_csv('file path') 直接将CSV 保存在云存储桶中。将您的 gcs 存储桶路由放在文件路径的位置。

例如 - df.to_csv('gs://bucketname/filename.csv')

【讨论】:

    猜你喜欢
    • 2016-08-28
    • 2020-06-13
    • 1970-01-01
    • 2020-02-17
    • 2023-03-08
    • 2023-03-14
    • 2019-02-26
    • 2014-01-05
    • 2018-10-09
    相关资源
    最近更新 更多