【发布时间】:2021-10-24 07:03:40
【问题描述】:
我似乎无法弄清楚我认为应该是什么简单的操作,以实例化我创建的类的一些任意列表(或其他容器,可能会随着时间而改变)。 播放示例:
import pandas as pd
df = pd.DataFrame([['helen', 'peanut', 3],['helen', 'butter', 7],['agnes', 'tuna', 5]], columns=['registered_to', 'cat_name', 'sale_price'])
cat_owners = df.registered_to.unique()
class CatOwner():
def __init__(self, name):
self.name=name
self.spent_on_cats = df.loc[df.registered_to==name]['sale_price'].sum()
for owner in cat_owners:
owner = CatOwner(owner) # I know this doesn't work.
cat_owners = [CatOwner(name) for name in cat_owners] #this gets me close(感谢@Tim Roberts 的建议),但还没有。
helen.spent_on_cats #desired output = 10,而不是错误
cat_owners.helen.spent_on_cats #如果我必须这样做,那很好,但这也不起作用(首选第一种方式),错误
感谢您的帮助!
【问题讨论】:
标签: python pandas class instance