Python 为类实例指定一个列表
我想获取一个各种变量名的列表,并将它们作为实例变量分配给一个类 此外,我还想从数据库中为这些实例变量分配属性 例如:我有一个带有标题的数据帧('col1','col2','col3','col4')。每一行都应该是一个类实例,每一列都应该是该类的实例变量。然后,应将每行中的值作为每个类实例的属性分配给每个实例变量 我怎样才能做到这一点 以下是变量列表:Python 为类实例指定一个列表,python,variables,object,instance-variables,Python,Variables,Object,Instance Variables,我想获取一个各种变量名的列表,并将它们作为实例变量分配给一个类 此外,我还想从数据库中为这些实例变量分配属性 例如:我有一个带有标题的数据帧('col1','col2','col3','col4')。每一行都应该是一个类实例,每一列都应该是该类的实例变量。然后,应将每行中的值作为每个类实例的属性分配给每个实例变量 我怎样才能做到这一点 以下是变量列表: Index(['Id', 'MSSubClass', 'MSZoning', 'LotFrontage', 'LotArea', 'Street
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)
这是一个自然适合s
输出:
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)
您可以使用
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')]
答案:在这篇文章中,“对象”是从数据帧自动创建的。而不必单独定义每个对象。例如:
>>类AllMyFields:。。。定义初始化(self,dictionary):。。。对于字典中的k,v.items():。。。setattr(self,k,v)…>>o=AllMyFields({'a':1,'b':2})>>>o.a1
必须将对象命名为“0”。我希望这些对象成为我可以随意调用的索引,当你这样做时,people=[Person(**x)代表df中的x.to_dict('df')]
x是什么意思?这是说“所有类实例”。当我运行此命令时,我收到以下错误。TypeError:**后的type对象参数必须是映射,而不是str@ClayChester,应该是df.to dict('records')
,而不是df.to dict('df')
。请查看以下文档:
class Person(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
people = [Person(**x) for x in df.to_dict('records')]