【问题标题】:How to write a pandas dataframe to_json() to s3 in json format如何以 json 格式将 pandas 数据帧 to_json() 写入 s3
【发布时间】:2021-04-19 00:04:11
【问题描述】:

我有一个创建数据框的 AWS lambda 函数,我需要将此文件写入 S3 存储桶。

import pandas as pd
import boto3
import io

# code to get the df

destination = "output_" + str(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')) + '.json'

df.to_json(destination) # this file should be written to S3 bucket

【问题讨论】:

    标签: python json pandas amazon-s3 aws-lambda


    【解决方案1】:

    以下代码在AWS Lambda 中运行,并将json 文件上传到S3。

    Lambda 角色应具有 S3 访问权限。

    import pandas as pd
    import boto3
    import io
    
    # code to get the df
    
    destination = "output_" + str(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')) + '.json'
    
    json_buffer = io.StringIO()
    
    df.to_json(json_buffer)
    
    s3 = boto3.resource('s3')
    my_bucket = s3.Bucket('my-bucket-name')
    
    my_bucket.put_object(Key=destination, Body=json_buffer.getvalue())
    
    
    

    【讨论】:

    • 成功了。 StackOverflow 上的所有其他 s3/json 答案都与 df.to_json 部分不一致,这对我的问题来说是必须的。谢谢。
    【解决方案2】:

    您也可以使用以下代码

    #Creating Session using Boto3
    
    session = boto3.Session(
    aws_access_key_id='<key ID>',
    aws_secret_access_key='<secret_key>'
    )
     
    #Create s3 session with boto3
    
    s3 = session.resource('s3')
     
    json_buffer = io.StringIO()
     
    # Create dataframe and convert to pandas
    df = spark.range(4).withColumn("organisation", lit("stackoverflow"))
    df_p = df.toPandas()
    df_p.to_json(json_buffer, orient='records')
     
    #Create s3 object
    object = s3.Object('<bucket-name>', '<JSON file name>')
     
    #Put the object into bucket
    result = object.put(Body=json_buffer.getvalue())
    

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 1970-01-01
      • 2020-07-29
      • 2017-08-13
      • 2019-09-23
      • 2023-04-03
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      相关资源
      最近更新 更多