gpt4 book ai didi

python - 构建所选特征的字典

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:25 25 4
gpt4 key购买 nike

我有 20K 个对象和列表中提供的一组功能。我需要从每个对象中提取这些特征并将它们保存到字典中。每个对象都有近 100 个特征。

例如:

# object1
Object1.Age = '20'
Object1.Gender = 'Female'
Object1.DOB = '03/05/1997'
Object1.Weight = '130lb'
Object1.Height = '5.5'

#object2
Object1.Age = '22'
Object1.Gender = 'Male'
Object1.DOB = '03/05/1995'
Object1.Weight = '145lb'
Object1.Height = '5.8'

#object3
Object1.Age = '22'
Object1.Gender = 'Male'
Object1.DOB = '03/05/1995'
Object1.Weight = '145lb'

#object4
...

以及我需要从每个对象中提取的功能列表(此列表可能会更改,因此我需要代码对此保持灵活):

features = ['Gender', 
'DOB',
'Height']

目前,我正在使用此函数来捕获每个对象所需的所有功能:

def get_features(obj, features):
return {f: getattr(obj, f) for f in features}

如果所有对象都具有我想要的所有功能,则此功能可以完美运行。但有些对象并不具备所有功能。例如,object3 没有名为“Height”的字段。如何将 NaN 作为字典中丢失文件的值,以便防止出现错误?

最佳答案

Python getattr documentation:

getattr(object, name[, default]) Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

你可以这样做:

def get_features(obj, features):
return {f: getattr(obj, f, float('Nan')) for f in features}

关于python - 构建所选特征的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222198/

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