【问题标题】:Feeding a list of prospective objects into a class to be instantiated将预期对象列表输入到要实例化的类中
【发布时间】: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


    【解决方案1】:

    您的问题中显示的列表理解将为您提供(显然)对 CatOwner 对象的引用列表。

    通过将理解分配给理解中使用的变量,您确实会混淆问题。

    也许这会有所帮助,因为您的最终目标并不完全清楚:

    import pandas as pd
    
    class CatOwner():
        def __init__(self, name, df):
            self.name = name
            self.spent_on_cats = df.loc[df.registered_to == name]['sale_price'].sum()
    
    df = pd.DataFrame([['helen', 'peanut', 3],
                    ['helen', 'butter', 7],
                    ['agnes', 'tuna', 5]],
                    columns=['registered_to', 'cat_name', 'sale_price'])
    
    for catowner in [CatOwner(name, df) for name in df.registered_to.unique()]:
        print(f'{catowner.name} spent {catowner.spent_on_cats} on cats')
    

    注意对数据框的引用是如何作为参数传递给类构造函数的。尽管 df 在您的原始代码范围内可用,但当您重新构建程序时,您很容易发现它突然超出范围,您的程序将中断。 IMO 最好这样做

    【讨论】:

    • 终极目标...说实话,我正试图将我组织 25 年历史的 excel 书带入下一代。同一个人一直在那里。他们愿意学习,但是,在 SQL 的帮助下,连接各种 Excel 书籍的重要网络的压力很大。我在这里尝试创建的对象是这一切的中心。它们很容易拥有数百个属性和方法/函数。
    猜你喜欢
    • 1970-01-01
    • 2019-02-07
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2015-07-29
    相关资源
    最近更新 更多