分组并查找属于 n 个唯一最大值的所有值

DGS*_*DGS 6 python pandas-groupby

我的数据框:

data = {'Input':[133217,133217,133217,133217,133217,133217,132426,132426,132426,132426,132426,132426,132426,132426],
 'Font':[30,25,25,21,20,19,50,50,50,38,38,30,30,29]}

     Input  Font
0   133217    30
1   133217    25
2   133217    25
3   133217    21
4   133217    20
5   133217    19
6   132426    50
7   132426    50
8   132426    50
9   132426    38
10  132426    38
11  132426    30
12  132426    30
13  132426    29
Run Code Online (Sandbox Code Playgroud)

我想创建一个仅包含Font中属于 3 个唯一最大值的值的新数据框。例如,输入 133217 的 3 个最大字体值为 30、25、21。

预期输出:

op_data = {'Input':[133217,133217,133217,133217,132426,132426,132426,132426,132426,132426,132426],
 'Font':[30,25,25,21,50,50,50,38,38,30,30]}

     Input  Font
0   133217    30
1   133217    25
2   133217    25
3   133217    21
4   132426    50
5   132426    50
6   132426    50
7   132426    38
8   132426    38
9   132426    30
10  132426    30
Run Code Online (Sandbox Code Playgroud)

我已经用来自熊猫的 groupby 尝试过这个:

df = pd.DataFrame(data)
df['order'] = df.groupby('Input').cumcount()+1
Run Code Online (Sandbox Code Playgroud)

然后我考虑了 1,2,3 个值df['order'],但没有按计划进行。有什么替代方法吗?

Myk*_*tko 3

您可以找到每个组的唯一值,获取包含三个最大值的列表并选择此列表中的行:

df.groupby('Input')['Font'].\
apply(lambda x: x[x.isin(np.sort(x.unique())[-3:])]).\
reset_index(level=0)
Run Code Online (Sandbox Code Playgroud)

输出:

     Input  Font
6   132426    50
7   132426    50
8   132426    50
9   132426    38
10  132426    38
11  132426    30
12  132426    30
0   133217    30
1   133217    25
2   133217    25
3   133217    21
Run Code Online (Sandbox Code Playgroud)