猿问

用for循环简化重复乘法?

有没有更优雅的方式来编写这段代码?我一遍又一遍地做同样的手术,所以感觉好像有,但我想不起来。


成人是熊猫数据框。权重是人的样本权重,每个 ped 变量代表不同的残疾类型。


total_cognitive_m = (adults.weight * (adults.pedisrem==1)).sum()/1e6

total_mobility_m = (adults.weight * (adults.pedisout==1)).sum()/1e6

total_self_care_m = (adults.weight * (adults.pedisdrs==1)).sum()/1e6

total_physical_m = (adults.weight * (adults.pedisphy==1)).sum()/1e6 

total_vision_m = (adults.weight * (adults.pediseye==1)).sum()/1e6

total_hearing_m = (adults.weight* (adults.pedisear==1)).sum()/1e6

total_disabled_m = (adults.weight * adults.disabled).sum()/1e6


慕的地6264312
浏览 115回答 3
3回答

慕尼黑8549860

如果您可以创建一个函数来减少重复代码,它会有所帮助: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"])

有只小跳蛙

此代码假定属性始终存在于 adults 变量中。'''The common behaviour of picking an attribute on adult&nbsp;like pedisrem and doing ( adult.weights * <attribute of adults> == 1).sum()/1e6has been achieved using list comprehension, we store those attributesin 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, \&nbsp;total_physical_m, total_vision_m, total_hearing_m =&nbsp;[(getattr(adults, multiplier) * getattr(adults, var) == 1).sum()/1e6&nbsp;for var in equalsToOne]total_disabled_m = (adults.weight * adults.disabled).sum()/1e6

一只甜甜圈

你可以定义一些集合来迭代你的数据,你可以使用一个元组来声明每个项目的属性adults.pedisrem,adults.pedisout,adults.pedisdrs, ...然后使用一个数组来存储每个结果properties = ("pedisrem","pedisout","pedisdrs")totalValues = ("total_cognitive_m","total_mobility_m","total_self_care_m")relationShip = {}i = 0for item in properties:&nbsp; &nbsp; relationShip[totalValues[i]]&nbsp; = (adults.weight * (adults[item]==1)).sum()/1e6&nbsp; &nbsp; i = i + 1;print(relationShip);
随时随地看视频慕课网APP

相关分类

Python
我要回答