我有一个 Julia 矩阵(当然,如果有帮助的话,我可以将其放入数据帧中),并且我想删除所有具有 NaN 值的行和列。谷歌似乎没有帮助。在 pandas 中,这是微不足道的:df.dropna().dropna(axis=1)
最佳答案
这是 DataFrames.jl 的答案。要删除具有缺失值的行和列,请分别执行以下操作:
julia> using DataFrames
julia> df = DataFrame(a=[1, 2, missing], b=[1, missing, 3], c=[1, 2, 3])
3×3 DataFrame
Row │ a b c
│ Int64? Int64? Int64
─────┼─────────────────────────
1 │ 1 1 1
2 │ 2 missing 2
3 │ missing 3 3
julia> dropmissing(df)
1×3 DataFrame
Row │ a b c
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 1 1
julia> df[all.(!ismissing, eachrow(df)), :] # the same using 2-dimensional indexing
1×3 DataFrame
Row │ a b c
│ Int64? Int64? Int64
─────┼───────────────────────
1 │ 1 1 1
julia> select(df, all.(!ismissing, eachcol(df)))
3×1 DataFrame
Row │ c
│ Int64
─────┼───────
1 │ 1
2 │ 2
3 │ 3
julia> df[:, all.(!ismissing, eachcol(df))] # the same using 2-dimensional indexing
3×1 DataFrame
Row │ c
│ Int64
─────┼───────
1 │ 1
2 │ 2
3 │ 3
请注意,删除行比删除列容易得多。原因是 DataFrames.jl 中的设计决策是大多数函数将数据帧视为行的集合,dropmissing
函数就是这种情况的一个示例。
主要的异常(exception)是:
- 索引(始终是二维的)
选择
、变换
和组合
适用于列的函数
对于矩阵来说,这是类似的,但由于它们不像数据框那样偏爱行而不是列,您可以这样做,例如:
julia> mat = Matrix(df)
3×3 Array{Union{Missing, Int64},2}:
1 1 1
2 missing 2
missing 3 3
julia> mat[all.(!ismissing, eachrow(df)), :]
1×3 Array{Union{Missing, Int64},2}:
1 1 1
julia> mat[:, all.(!ismissing, eachcol(df))]
3×1 Array{Union{Missing, Int64},2}:
1
2
3
关于pandas - Julia 中 pandas `dropna` 的类似物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65567382/