dplyr中top_n()的等价物是什么?

2024-04-27 05:10:55 发布

您现在位置:Python中文网/ 问答频道 /正文

dplyr中top_n()的等价物是什么

在R dplyr 0.8.5中:

> df <- data.frame(x = c(10, 4, 1, 6, 3, 1, 6))
> df %>% top_n(2, wt=x)
   x
1 10
2  6
3  6

正如dplyr文档所强调的,注意我们在这里得到的值不止2个,因为有一个关系:top_n()要么接受所有带值的行,要么不接受

我在熊猫1.0.1中的尝试:

df = pd.DataFrame({'x': [10, 4, 1, 6, 3, 1, 6]})
df = df.sort_values('x', ascending=False)
df.groupby('x').head(2)

结果:

    x
0  10
3   6
6   6
1   4
4   3
2   1
5   1

预期成果:

   x
1 10
2  6
3  6

Tags: 文档falsedataframedfdata关系topsort
3条回答

IUC,用^{}尝试^{}

df[df['x'].isin(df['x'].nlargest(2))]#.reset_index(drop=True)

    x
0  10
3   6
6   6

top_n中的dplyrslice_max/slice_min取代。见:

https://dplyr.tidyverse.org/reference/top_n.html

使用python中的^{},您可以用类似的方式执行此操作:

>>> import pandas as pd
>>> from datar.all import f, slice_max
>>> 
>>> df = pd.DataFrame({'x': [10, 4, 1, 6, 3, 1, 6]})
>>> df
        x
  <int64>
0      10
1       4
2       1
3       6
4       3
5       1
6       6
>>> df >> slice_max(n=3, order_by=f.x)
        x
  <int64>
0      10
3       6
6       6

免责声明:我是datar软件包的作者

^{}中使用参数keep='all',不需要在此处排序:

df = df.nlargest(2, 'x', keep='all')
print(df)

    x
0  10
3   6
6   6

相关问题 更多 >