DataFrame 中每组的行数

Row Number per Group in DataFrame

我有一个朱莉娅DataFrame

using DataFrames
df = DataFrame(a = [1,1,1,2,2,2,2], b = 1:7)

7×2 DataFrame
 Row │ a      b     
     │ Int64  Int64 
─────┼──────────────
   1 │     1      1
   2 │     1      2
   3 │     1      3
   4 │     2      4
   5 │     2      5
   6 │     2      6
   7 │     2      7

并希望创建一个包含每组行号的新列。它应该是这样的

7×2 DataFrame
 Row │ a      b      c 
     │ Int64  Int64  Int64
─────┼──────────────────────
   1 │     1      1      1
   2 │     1      2      2
   3 │     1      3      3
   4 │     2      4      4
   5 │     2      5      1
   6 │     2      6      2
   7 │     2      7      3

我对任何解决方案都持开放态度,但我特别希望找到与 Chain 软件包一起使用的 DataFramesMeta 解决方案。 Rdplyr 有一个名为 n() 的简单函数就是这样做的。感觉Julia里面一定有类似的东西

做:

julia> using DataFrames, DataFramesMeta

julia> df = DataFrame(a = [1,1,1,2,2,2,2], b = 1:7)
7×2 DataFrame
 Row │ a      b
     │ Int64  Int64
─────┼──────────────
   1 │     1      1
   2 │     1      2
   3 │     1      3
   4 │     2      4
   5 │     2      5
   6 │     2      6
   7 │     2      7

julia> @chain df begin
           groupby(:a)
           @transform(:c = eachindex(:b))
       end
7×3 DataFrame
 Row │ a      b      c
     │ Int64  Int64  Int64
─────┼─────────────────────
   1 │     1      1      1
   2 │     1      2      2
   3 │     1      3      3
   4 │     2      4      1
   5 │     2      5      2
   6 │     2      6      3
   7 │     2      7      4

在即将发布的 DataFrames.jl 1.4 版本中,它会更加简单,请参阅 https://github.com/JuliaData/DataFrames.jl/pull/3001

(不同之处在于,在这种情况下,您不必将列名作为 :b 传递,而是编写 :c = $eachindex