Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a pandas dataframe into a list of named tuple [duplicate]

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)]
like image 737
Michael Avatar asked Nov 21 '19 13:11

Michael


2 Answers

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)]
like image 53
jezrael Avatar answered Sep 30 '22 11:09

jezrael


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)]
like image 44
Dani Mesejo Avatar answered Sep 30 '22 10:09

Dani Mesejo