我有一个数据集,其特征为“ abdomcirc”,每个ChildID都有多个值,例如:
ChildID abdomcirc
0 1 273
1 1 267
2 1 294
3 2 136
4 2 248
我想为给定的每个孩子id的腹围值列表计算值的范围。所以我想得到这些结果:
ChildID range
0 1 27
1 2 112
所以我首先尝试了这个:
df["range"] = df.groupby('ChildID')["mussabdomcirc"].transform('range')
但是我收到此错误 ValueError:'range'不是transform(name)的有效函数名
因此,正如对此question的回答所建议的那样,我尝试了以下行:
df["range"] = df.groupby('ChildID').apply(lambda x: x.High.max() - x.Low.min())
但是我得到了这个错误: AttributeError:“ DataFrame”对象没有属性“ High”
不确定为什么会出现此错误。关于如何成功计算数据框中一组值的范围的任何建议?
答案 0 :(得分:2)
numpy.ptp
中有一个功能
s=df.groupby('ChildID')['abdomcirc'].apply(np.ptp).to_frame('range').reset_index()
Out[75]:
ChildID range
0 1 27
1 2 112
修正您的代码
df.groupby('ChildID').apply(lambda x: x.abdomcirc.max() - x.abdomcirc.min())
答案 1 :(得分:1)
phpinfo();
不在High
中,请用您的专栏更改df
High