[Python] How to convert a list of Pydantic BaseModels to Pandas Dataframe

Discussão em 'Python' iniciado por Stack, Julho 28, 2025.

  1. Stack

    Stack Membro Participativo

    I can't seem to find any built-in way of simply converting a list of Pydantic BaseModels to a Pandas Dataframe.

    from pydantic import BaseModel
    import pandas as pd

    class SomeModel(BaseModel):
    col1: str
    col2: str

    data = [SomeModel(**{'col1': 'foo', 'col2': 'bar'})] * 10
    pd.DataFrame(data)


    Output

    >> 0 1
    >> 0 (col1, foo) (col2, bar)
    >> 1 (col1, foo) (col2, bar)
    >> ...


    In this way the columns are loaded as data. A workaround is to do the following

    pd.DataFrame([model.dict() for model in data])


    Output

    >> col1 col2
    >> 0 foo bar
    >> 1 foo bar
    >> ...


    However this method is a bit slow for larger amounts of data. Is there a faster way?

    Continue reading...

Compartilhe esta Página