【问题标题】:Read excel file from S3 into Pandas DataFrame将 S3 中的 excel 文件读入 Pandas DataFrame
【发布时间】:2019-06-08 16:16:51
【问题描述】:

我有一个 SNS 通知设置,当 .xlsx 文件上传到 S3 存储桶时会触发 Lambda 函数。

lambda 函数将 .xlsx 文件读入 Pandas DataFrame。

import os 
import pandas as pd
import json
import xlrd
import boto3

def main(event, context):
    message = event['Records'][0]['Sns']['Message']
    parsed_message = json.loads(message)
    src_bucket = parsed_message['Records'][0]['s3']['bucket']['name']
    filepath = parsed_message['Records'][0]['s3']['object']['key']

    s3 = boto3.resource('s3')
    s3_client = boto3.client('s3')

    obj = s3_client.get_object(Bucket=src_bucket, Key=filepath)
    print(obj['Body'])

    df = pd.read_excel(obj, header=2)
    print(df.head(2))

我收到如下错误:

Invalid file path or buffer object type: <type 'dict'>: ValueError
Traceback (most recent call last):
File "/var/task/handler.py", line 26, in main
df = pd.read_excel(obj, header=2)
File "/var/task/pandas/util/_decorators.py", line 178, in wrapper
return func(*args, **kwargs)
File "/var/task/pandas/util/_decorators.py", line 178, in wrapper
return func(*args, **kwargs)
File "/var/task/pandas/io/excel.py", line 307, in read_excel
io = ExcelFile(io, engine=engine)
File "/var/task/pandas/io/excel.py", line 376, in __init__
io, _, _, _ = get_filepath_or_buffer(self._io)
File "/var/task/pandas/io/common.py", line 218, in get_filepath_or_buffer
raise ValueError(msg.format(_type=type(filepath_or_buffer)))
ValueError: Invalid file path or buffer object type: <type 'dict'>

我该如何解决这个问题?

【问题讨论】:

    标签: python pandas amazon-s3 lambda


    【解决方案1】:

    这很正常! obj 是字典,你试过吗?

    df = pd.read_excel(obj['body'], header=2)
    

    【讨论】:

    • 就是这样。 df = pd.read_excel(obj['body'], header=2)。您的帖子缺少“body”的关闭]。感谢您的帮助。
    • 我的荣幸 :) P.S:我已经添加了]
    【解决方案2】:

    Pandas 现在支持 s3 URL 作为文件路径,因此它可以直接从 s3 读取 excel 文件,而无需先下载。

    查看此处的 CSV 示例 - https://stackoverflow.com/a/51777553/52954

    【讨论】:

      【解决方案3】:

      试试pd.read_excel(obj['Body'].read())

      【讨论】:

        【解决方案4】:

        如果obj是字典,你可以试试

        df = pd.DataFrame.from_dict(obj)
        

        Documentation here 如果您需要更改参数。

        【讨论】:

          猜你喜欢
          • 2020-08-27
          • 2013-12-27
          • 2016-02-22
          • 2021-11-24
          • 1970-01-01
          • 1970-01-01
          • 2021-05-22
          • 2017-11-14
          • 1970-01-01
          相关资源
          最近更新 更多