2017-10-08 36 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