将熊猫数据框转换为命名元组列表

时间:2019-11-21 13:03:28

标签: python pandas tuples namedtuple

我正在寻找将pandas DataFrame转换为类型为NamedTuple的列表的最有效方法-以下是具有预期输出的简单示例。 我想使正确的类型转换与数据框中定义的类型保持一致。

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)]

2 个答案:

答案 0 :(得分:7)

DataFrame.itertuplesname参数一起使用,并为省略索引添加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)]

如果在命名元组中需要小写值nameage,请添加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)]

答案 1 :(得分:4)

使用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)

输出

[Person(Name='tom', Age=10), Person(Name='nick', Age=15), Person(Name='juli', Age=14)]