我正在寻找将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)]
答案 0 :(得分:7)
将DataFrame.itertuples
与name
参数一起使用,并为省略索引添加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)]
如果在命名元组中需要小写值name
和age
,请添加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)]