我正在尝试对一组事物进行分组,并根据最小值、最大值和平均值(最小值和最大值)动态地在组内执行剪切。
我的数据集看起来像这样:
Country Value
Uganda 210
Kenya 423
Kenya 315
Tanzania 780
Uganda 124
Uganda 213
Tanzania 978
Kenya 524
Run Code Online (Sandbox Code Playgroud)
我期望的是每个值落在哪个范围内,高于或低于中值:
Country Value Range
Uganda 210 (168.5, 213)
Uganda 124 (124, 168.5)
Uganda 213 (168.5, 213)
Kenya 423 (419.5, 524)
Kenya 315 (315, 419.5)
Kenya 524 (419.5, 524)
Tanzania 780 (780, 879)
Tanzania 978 (879, 980)
Run Code Online (Sandbox Code Playgroud)
如果我通过循环迭代每个组来实现这一点,我就能够实现这一点。我还能够根据整个数据集的最小值和最大值来实现切割,但不能根据单个组来实现。但是,我想知道是否可以使用 pandas 在一行或两行中完成而不使用循环。
我就是这样做的:
df['range'] = df.groupby('country')[['value']].transform(lambda x: pd.cut(x, bins = 2).astype(str))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17942 次 |
| 最近记录: |