3 回答
TA贡献1818条经验 获得超11个赞
如果您可以创建一个函数来减少重复代码,它会有所帮助:
def calc(adults, name):
return (adults.weight * (getattr(adults,name)==1)).sum() / 1e6
但是如果您使用许多单独的变量,您仍然需要为每个单独的赋值语句(这里不包括某些高级但“hacky”的解决方案):
total_cognitive_m = calc(adults, 'pedisrem')
total_mobility_m = calc(adults, 'pedisout')
... etc ...
如果您可以将输出数据放入某种集合(例如字典)中,那就更好了。在这种情况下,您可以这样做:
inputs_to_use = {
'total_cognitive_m': 'pedisrem',
'total_mobility_m': 'pedisout',
... etc ...
}
然后,您可以使用以下方法制作输出字典:
outputs = { key: calc(adults, name)
for key, name in inputs_to_use.items() }
然后查找值,例如通过做
print(outputs["total_cognitive_m"])
TA贡献1824条经验 获得超8个赞
此代码假定属性始终存在于 adults 变量中。
'''
The common behaviour of picking an attribute on adult
like pedisrem and doing ( adult.weights * <attribute of adults> == 1).sum()/1e6
has been achieved using list comprehension, we store those attributes
in equalsToOne array and iterate over them.
'''
multiplier = 'weight'
equalsToOne = ['pedisrem', 'pedisout', 'pedisdrs', 'pedisphy', 'pediseye', 'pedisear']
total_cognitive_m, total_mobility_m, total_self_care_m, \
total_physical_m, total_vision_m, total_hearing_m =
[(getattr(adults, multiplier) * getattr(adults, var) == 1).sum()/1e6
for var in equalsToOne]
total_disabled_m = (adults.weight * adults.disabled).sum()/1e6
TA贡献1836条经验 获得超5个赞
你可以定义一些集合来迭代你的数据,你可以使用一个元组来声明每个项目的属性adults.pedisrem,adults.pedisout,adults.pedisdrs, ...然后使用一个数组来存储每个结果
properties = ("pedisrem","pedisout","pedisdrs")
totalValues = ("total_cognitive_m","total_mobility_m","total_self_care_m")
relationShip = {}
i = 0
for item in properties:
relationShip[totalValues[i]] = (adults.weight * (adults[item]==1)).sum()/1e6
i = i + 1;
print(relationShip);
添加回答
举报