跳过最后N行Julia Dataframe



我在Julia中从Dataframe中删除最后N行有一个问题。

N_SKIP = 3
df = DataFrame(:col1=>1:10,:col2=>21:30)
N = nrow(df)

原始示例

10×2 DataFrame
│ Row │ col1  │ col2  │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 21    │
│ 2   │ 2     │ 22    │
│ 3   │ 3     │ 23    │
│ 4   │ 4     │ 24    │
│ 5   │ 5     │ 25    │
│ 6   │ 6     │ 26    │
│ 7   │ 7     │ 27    │
│ 8   │ 8     │ 28    │
│ 9   │ 9     │ 29    │
│ 10  │ 10    │ 30    │

我想获得第一个N - N_SKIP行,在这个例子中,id在1:7范围内的行。

结果我试图实现与N = 3:

7×2 DataFrame
│ Row │ col1  │ col2  │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 21    │
│ 2   │ 2     │ 22    │
│ 3   │ 3     │ 23    │
│ 4   │ 4     │ 24    │
│ 5   │ 5     │ 25    │
│ 6   │ 6     │ 26    │
│ 7   │ 7     │ 27    │

我可以使用first(df::AbstractDataFrame, n::Integer)并在参数中传递剩余的行数。它可以工作,但似乎不正确。

julia> N_SKIP = 3
julia> df = DataFrame(:col1=>1:10,:col2=>21:30)
julia> N = nrow(df)
julia> first(df,N - N_SKIP)
7×2 DataFrame
│ Row │ col1  │ col2  │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 21    │
│ 2   │ 2     │ 22    │
│ 3   │ 3     │ 23    │
│ 4   │ 4     │ 24    │
│ 5   │ 5     │ 25    │
│ 6   │ 6     │ 26    │
│ 7   │ 7     │ 27    │

有三种方法可以做到这一点(取决于你想要什么)。

  1. 创建一个新的数据帧:
julia> df[1:end-3, :]
7×2 DataFrame
Row │ col1   col2
│ Int64  Int64
─────┼──────────────
1 │     1     21
2 │     2     22
3 │     3     23
4 │     4     24
5 │     5     25
6 │     6     26
7 │     7     27
julia> first(df, nrow(df) - 3)
7×2 DataFrame
Row │ col1   col2
│ Int64  Int64
─────┼──────────────
1 │     1     21
2 │     2     22
3 │     3     23
4 │     4     24
5 │     5     25
6 │     6     26
7 │     7     27
  1. 创建一个数据帧的视图:
julia> first(df, nrow(df) - 3, view=true)
7×2 SubDataFrame
Row │ col1   col2
│ Int64  Int64
─────┼──────────────
1 │     1     21
2 │     2     22
3 │     3     23
4 │     4     24
5 │     5     25
6 │     6     26
7 │     7     27
julia> @view df[1:end-3, :]
7×2 SubDataFrame
Row │ col1   col2
│ Int64  Int64
─────┼──────────────
1 │     1     21
2 │     2     22
3 │     3     23
4 │     4     24
5 │     5     25
6 │     6     26
7 │     7     27
  1. 就地更新源数据帧(或者可以使用deleteat!,这取决于对您更方便):
julia> keepat!(df, 1:nrow(df)-3)
7×2 DataFrame
Row │ col1   col2
│ Int64  Int64
─────┼──────────────
1 │     1     21
2 │     2     22
3 │     3     23
4 │     4     24
5 │     5     25
6 │     6     26
7 │     7     27

最新更新