如何在 FastAPI 中上传文件并将其转换为 Pandas Dataframe?

How to upload a file in FastAPI and convert it into a Pandas Dataframe?

如何使用以下代码将文件转换为数据帧?

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):
    df = pd.read_csv("")
    print(df)
    return {"filename": file.filename}

选项 1

将字节转换为字符串,然后将其加载到in-memory文本缓冲区(即StringIO),可以将其转换为数据帧:

from fastapi import FastAPI, File, UploadFile
import pandas as pd
from io import StringIO

app = FastAPI()

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    s = str(contents,'utf-8')
    data = StringIO(s) 
    df = pd.read_csv(data)
    data.close()
    return {"filename": file.filename}

选项 2

改用 in-memory 字节缓冲区(即 BytesIO),从而省去了将字节转换为字符串的步骤:

from fastapi import FastAPI, File, UploadFile
import pandas as pd
from io import BytesIO

app = FastAPI()

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    data = BytesIO(contents)
    df = pd.read_csv(data)
    data.close()
    return {"filename": file.filename}