[Python] Python pandas: construct list dataclass objects from each row of a dataframe

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    A consistent answer seems to be to avoid iterating over rows while working with Pandas. I'd like to understand how I can do so in the following case.

    from typing import List

    @dataclass
    class Person:
    id: int
    name: str
    age: int

    persons_df = pd.DataFrame(data={'id': [1, 2, 3], 'name': ['A', 'B', 'C'], 'age': [32, 44, '86']})

    persons_list: List[Person] = [] #populate this list with Person objects, created from the dataframe above

    # my approach is to use iterrows()
    for row in persons_df.itertuples():
    person = Person(row.id, row.name, int(row.age)) # type: ignore
    plist.append(person)


    I'd like to find an option which can avoid the iterrows, and if possible, be done in a manner that has some type safety built in (avoid the mypy ignore comment).

    thanks!

    Continue reading...

Compartilhe esta Página