What is the proper way to query top N rows by group in python datatable?
For example to get top 2 rows having largest v3
value by id2, id4
group I would do pandas expression in the following way:
df.sort_values('v3', ascending=False).groupby(['id2','id4']).head(2)
in R using data.table
:
DT[order(-v3), head(v3, 2L), by=.(id2, id4)]
or in R using dplyr
:
DF %>% arrange(desc(v3)) %>% group_by(id2, id4) %>% filter(row_number() <= 2L)
Example data and expected output using pandas:
import datatable as dt
dt = dt.Frame(id2=[1, 2, 1, 2, 1, 2], id4=[1, 1, 1, 1, 1, 1], v3=[1, 3, 2, 3, 3, 3])
df = dt.to_pandas()
df.sort_values('v3', ascending=False).groupby(['id2','id4']).head(2)
# id2 id4 v3
#1 2 1 3
#3 2 1 3
#4 1 1 3
#2 1 1 2
DataFrame
? – Algebradatatable
notDataFrame
, added link in question so it is more clear. – Inclinatory