【发布时间】:2020-03-13 12:40:34
【问题描述】:
我有一个人类:
class Person:
def __init__(self, name, score):
self.name=name
self.score=score
def to_dict(self):
return {
'name':self.name,
'score':self.score,
}
我正在制作一些 Person 对象并将它们添加到一个数组中:
a=Person("Sam", 2)
b=Person("Tim", 3)
people=[a,b]
现在使用 to_dict 方法从该数组中创建一个数据框
df=pd.DataFrame.from_records([s.to_dict() for s in people])
我想让这个数据框与对象同步,这样只要分数发生变化,它就会立即更新。
【问题讨论】:
-
您能否将您的
Person对象存储在DataFrame中?这可能允许您的属性被同步,具体取决于pandas是否复制(?) -
是的@dspencer,那太好了。据我所知,您只能在数据框中存储静态字段。我想我会编写函数来更新 df 并在每次有可能更改值时调用它。
-
根据我的快速测试,属性将传播回 DataFrame,稍后将发布示例
标签: python pandas dataframe data-science