为了账号安全,请及时绑定邮箱和手机立即绑定

用for循环简化重复乘法?

用for循环简化重复乘法?

慕的地6264312 2023-04-11 15:25:43
有没有更优雅的方式来编写这段代码?我一遍又一遍地做同样的手术,所以感觉好像有,但我想不起来。成人是熊猫数据框。权重是人的样本权重,每个 ped 变量代表不同的残疾类型。total_cognitive_m = (adults.weight * (adults.pedisrem==1)).sum()/1e6total_mobility_m = (adults.weight * (adults.pedisout==1)).sum()/1e6total_self_care_m = (adults.weight * (adults.pedisdrs==1)).sum()/1e6total_physical_m = (adults.weight * (adults.pedisphy==1)).sum()/1e6 total_vision_m = (adults.weight * (adults.pediseye==1)).sum()/1e6total_hearing_m = (adults.weight* (adults.pedisear==1)).sum()/1e6total_disabled_m = (adults.weight * adults.disabled).sum()/1e6
查看完整描述

3 回答

?
慕尼黑8549860

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"])


查看完整回答
反对 回复 2023-04-11
?
有只小跳蛙

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


查看完整回答
反对 回复 2023-04-11
?
一只甜甜圈

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);


查看完整回答
反对 回复 2023-04-11
  • 3 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信