我在从 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 │
最佳答案
您可以通过三种方式来实现此目的(取决于您想要什么)。
- 创建一个新的数据框:
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
- 创建数据框 View :
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
- 就地更新源数据框(或者可以使用
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
关于dataframe - 跳过 Julia Dataframe 的最后 N 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74657235/