2017-10-08 37 views
2

我想采取各种变量名称的列表,并指定它们作为实例变量的类。分配列表类的实例

此外,我也想从数据库属性分配给这些实例变量。

例如:我有一个标头数据帧,( 'COL1', 'COL2', 'COL3', 'COL4')。每行应该是一个类实例,每一列应该是该类的实例变量。然后,每行中的值,应分配给每个实例变量为每个类实例的属性。

我怎样才能做到这一点?

这里的变量列表:

Index(['Id', 'MSSubClass', 'MSZoning', 'LotFrontage', 'LotArea', 'Street', 
     'Alley', 'LotShape', 'LandContour', 'Utilities', 'LotConfig', 
     'LandSlope', 'Neighborhood', 'Condition1', 'Condition2', 'BldgType', 
     'HouseStyle', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd', 
     'RoofStyle', 'RoofMatl', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 
     'MasVnrArea', 'ExterQual', 'ExterCond', 'Foundation', 'BsmtQual', 
     'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinSF1', 
     'BsmtFinType2', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'Heating', 
     'HeatingQC', 'CentralAir', 'Electrical', '1stFlrSF', '2ndFlrSF', 
     'LowQualFinSF', 'GrLivArea', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath', 
     'HalfBath', 'BedroomAbvGr', 'KitchenAbvGr', 'KitchenQual', 
     'TotRmsAbvGrd', 'Functional', 'Fireplaces', 'FireplaceQu', 'GarageType', 
     'GarageYrBlt', 'GarageFinish', 'GarageCars', 'GarageArea', 'GarageQual', 
     'GarageCond', 'PavedDrive', 'WoodDeckSF', 'OpenPorchSF', 
     'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea', 'PoolQC', 
     'Fence', 'MiscFeature', 'MiscVal', 'MoSold', 'YrSold', 'SaleType', 
     'SaleCondition', 'SalePrice'], 
     dtype='object') 

下面是一个例子数据框:

import pandas as pd 
from numpy import nan 
d = {'name' : pd.Series(['steve', 'jeff', 'bob'], index=['1', '2', '3']), 
     ....:  'salary' : pd.Series([34, 85, 213], index=['1', '2', '3']), 'male' : pd.Series([1, nan, 0], index=['1', '2', '3']), 'score' : pd.Series([1.46, 0.8, 3.], index=['1', '2', '3'])} 

df = pd.DataFrame(d) 
+0

这是非常这个问题回答的一个副本:https://stackoverflow.com/questions/1639174/creating-class-instance-properties-from-a-dictionary – Bill

+1

[从字典中创建类的实例属性?]的可能的复制(HTTPS: //stackoverflow.com/questions/1639174/creating-class-instance-properties-from-a-dictionary) – toonarmycaptain

+0

在这个帖子中,“物”会自动从数据帧创建。而不必单独定义每个对象。例如:'>>>类AllMyFields: ... DEF __init __(个体,字典): ...为K,V在dictionary.items(): ... SETATTR(个体,K,V) ... >>> O = AllMyFields({ 'A':1, 'b':2}) >>> OA 1'具有为 “0” 我想这些对象是索引命名对象我可以随意 –

回答

1

这是一个自然选择namedtuple秒。

#! /usr/bin/env python3 


import collections 
import pandas as pd 


if __name__ == '__main__': 

    Person = collections.namedtuple('Person', 'male name salary score') 

    d = {'name': pd.Series(['steve', 'jeff', 'bob'], index=['1', '2', '3']), 
     'salary': pd.Series([34, 85, 213], index=['1', '2', '3']), 
     'male': pd.Series([1, float('NaN'), 0], index=['1', '2', '3']), 
     'score': pd.Series([1.46, 0.8, 3.], index=['1', '2', '3'])} 
    df = pd.DataFrame(d, columns=sorted(d.keys())) 
    print(df) 

    for row in df.values: 
     print(Person(*row.tolist())) 

输出:

male name salary score 
1 1.0 steve  34 1.46 
2 NaN jeff  85 0.80 
3 0.0 bob  213 3.00 
Person(male=1.0, name='steve', salary=34, score=1.46) 
Person(male=nan, name='jeff', salary=85, score=0.8) 
Person(male=0.0, name='bob', salary=213, score=3.0) 
1

您可以使用df.to_dict('records')生成词典列表,

[{'male': 1.0, 'name': 'steve', 'salary': 34, 'score': 1.46}, 
{'male': nan, 'name': 'jeff', 'salary': 85, 'score': 0.8}, 
{'male': 0.0, 'name': 'bob', 'salary': 213, 'score': 3.0}] 

然后,你可以做这样的事情来建立名单,

class Person(object):  
    def __init__(self, **kwargs): 
     self.__dict__.update(kwargs) 

people = [Person(**x) for x in df.to_dict('records')] 
+0

打电话的时候,你这样做,'人= [(X **)在df.to_dict X人( 'DF')]'什么** X是什么意思?是说“所有类实例”。当我运行这个我收到以下错误。类型错误:类型对象参数后**必须是一个映射,而不是str的 –

+0

@ClayChester,应该是'df.to_dict( '记录')','未df.to_dict( 'DF')'。看看对文档[DataFrame.to_dict()](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html) – Aldehir