I am looking for the most efficient way to convert a pandas DataFrame into a list of typed NamedTuple - below is a simple example with the expected output.
I would like to get the correct type conversion aligned with the type defined in the dataframe.
from typing import NamedTuple
import pandas as pd
if __name__ == "__main__":
    data = [["tom", 10], ["nick", 15], ["juli", 14]]
    People = pd.DataFrame(data, columns=["Name", "Age"])
    Person = NamedTuple("Person", [("name", str), ("age", int)])
    # ...
    # ...
    # expected output
    # [Person(name='tom', age=10), Person(name='nick', age=15), Person(name='juli', age=14)]
                Use DataFrame.itertuples with name parameter and for omit index add index=false:
tup = list(people.itertuples(name='Person', index=False))
print(tup)
[Person(Name='tom', Age=10), Person(Name='nick', Age=15), Person(Name='juli', Age=14)]
If need lowercase values name and age in namedtuples add rename:
tup = list(people.rename(columns=str.lower).itertuples(name='Person', index=False))
print(tup)
[Person(name='tom', age=10), Person(name='nick', age=15), Person(name='juli', age=14)]
                        Use itertuples:
import pandas as pd
data = [["tom", 10], ["nick", 15], ["juli", 14]]
people = pd.DataFrame(data, columns=["Name", "Age"])
result = list(people.itertuples(index=False, name='Person'))
print(result)
Output
[Person(Name='tom', Age=10), Person(Name='nick', Age=15), Person(Name='juli', Age=14)]
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With