python - 熊猫在每个组中获得最重要的不同记录
问题描述
在这种情况下,我想带来每个 id 的最高值,但数量不同。也就是说,我正在寻找 'id'=1 的 5 个最高值,'id'=2 的 3 个最高值,等等。我有这个代码,它只会给我每组带来固定数量的值。
import random
df = pd.DataFrame({'id':[1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4]})
df['value'] = np.random.randint(0, 99, df.shape[0])
df.groupby(['id']).apply(lambda x: x.nlargest(2,['value'])).reset_index(drop=True)
id = 1 --> 5
id = 2 --> 3
id = 3 --> 2
id = 4 --> 2
解决方案
国际大学联盟:
def my_largest(d):
# define a dictionary with the specific
# number of largest rows to grab for
# each `'id'`
nlim = {1: 5, 2: 3, 3: 2, 4: 2}
# When passing a dataframe from a
# `groupby` to the callable used in
# the `apply`, Pandas will attach an
# attribute `name` to that dataframe
# whose value is the disctint group
# the dataframe represents. In this
# case, that will be the `'id'` because
# we grouped by `'id'`
k = nlim[d.name]
return d.nlargest(k, ['value'])
df.groupby('id').apply(my_largest).reset_index(drop=True)
id value
0 1 96
1 1 83
2 1 58
3 1 49
4 1 43
5 2 66
6 2 40
7 2 33
8 3 90
9 3 54
10 4 83
11 4 23
同样的事情,但具有更通用的功能
现在这个函数可以接受任何规范字典。此外,我还包含了一个参数以'id'
在规范字典中不存在的情况下使用默认值。
def my_largest(d, nlrg_dict, nlrg_dflt=5, **kw):
k = nlrg_dict.get(d.name, nlrg_dflt)
return d.nlargest(k, **kw)
现在,您可以看到我们在函数之外定义字典...
nlim = {1: 5, 2: 3, 3: 2, 4: 2}
...并将其传递给函数apply
df.groupby('id').apply(
my_largest, nlrg_dict=nlim, columns=['value']
).reset_index(drop=True)
推荐阅读
- php - 从 Tinymce 转换富文本并使用它来填充 pdf 文档的一部分
- r - 在 R 中使用 predict() 重新生成 rpart() 模型时获得一致的分类
- c# - 如何通过 C# 代码在 C++ DLL 中为 char 数组(C-String)赋值
- javascript - jQuery each 在每个其他元素上运行函数
- java - Spring boot - 如何获取 WARN 的框架日志记录和 DEBUG 的应用程序日志记录
- bash - Bash:检查目录是否仅包含具有特定后缀的文件
- sql - 根据列值获取相交的行
- node.js - 当安装在另一个文件夹上时,我的 cli 引擎(npm 包)找不到读取文件的路径
- c++ - 如何在 C++ 中处理多个 opencv 版本
- c++ - 将 if constexpr() 与非 const 条件相结合