gpt4 book ai didi

python - 将 Pandas DataFrame 转换为对象列表

转载 作者:行者123 更新时间:2023-11-28 21:34:34 25 4
gpt4 key购买 nike

我想将 Pandas DataFrame 转换为对象列表。

这是我的课:

class Reading:

def __init__(self):
self.HourOfDay: int = 0
self.Percentage: float = 0

我阅读了 .to_dict,所以我尝试了
df.to_dict(into=Reading)

但它回来了
TypeError: unsupported type

我不需要元组列表或字典列表,而是阅读列表。到目前为止,我发现的每个问题似乎都与这两种情况有关。但我想要我自己的类型对象。

谢谢

最佳答案

具有包含两列 HourOfDay 和 Percentage 的数据框,以及类的参数化构造函数,您可以像这样定义一个 Object 列表:

 class Reading:

def __init__(self, h, p):
self.HourOfDay = h
self.Percentage = p

listOfReading= [(Reading(row.HourOfDay,row.Percentage)) for index, row in df.iterrows() ]

关于python - 将 Pandas DataFrame 转换为对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53192602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com