python - 构建所选特征的字典

标签 python dictionary missing-features

我有 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/

相关文章:

c++ - 类型删除映射的拷贝(分配)应该有多深

python - 在没有 math.ceil() 的情况下向上舍入数学计算?

python - numpy einsum() 可以执行外加法吗?

javascript - 在 Flask 应用程序中将变量从后端传递到前端

c++ - 为什么有些词会出现段错误?而其他人似乎工作正常

python - 字典问题(TypeError : string indices must be integers)

c# - 在缺少 setup.py 的 Windows 上构建 Apache QPID

Python比较运算符重载

sqlite - 如何处理 SQLite : disable triggers? 的缺失功能

java - apache poi jar 缺少类文件