How to get the first row of each group of a DataFrame?

Here are three options to get it:

julia> combine(groupby(df, :age)) do sdf
       sdf[argmax(sdf.height), :]
       end
4×3 DataFrame
│ Row │ age   │ sex    │ height  │
│     │ Int64 │ String │ Float64 │
├─────┼───────┼────────┼─────────┤
│ 1   │ 14    │ M      │ 179.193 │
│ 2   │ 16    │ M      │ 188.043 │
│ 3   │ 18    │ F      │ 181.994 │
│ 4   │ 20    │ M      │ 171.729 │

julia> combine(groupby(df, :age)) do sdf
       first(sort(sdf, :height, rev=true))
       end
4×3 DataFrame
│ Row │ age   │ sex    │ height  │
│     │ Int64 │ String │ Float64 │
├─────┼───────┼────────┼─────────┤
│ 1   │ 14    │ M      │ 179.193 │
│ 2   │ 16    │ M      │ 188.043 │
│ 3   │ 18    │ F      │ 181.994 │
│ 4   │ 20    │ M      │ 171.729 │

julia> combine(first, groupby(sort(df, :height, rev=true), :age))
4×3 DataFrame
│ Row │ age   │ sex    │ height  │
│     │ Int64 │ String │ Float64 │
├─────┼───────┼────────┼─────────┤
│ 1   │ 16    │ M      │ 188.043 │
│ 2   │ 18    │ F      │ 181.994 │
│ 3   │ 14    │ M      │ 179.193 │
│ 4   │ 20    │ M      │ 171.729 │

(the first one is fastest as it does not require sorting)

4 Likes