如何删除/删除 Julia 数据框中的空行和 NaN?

Moh*_* ah 4 julia julia-dataframe

我有一个 df ,其中包含nothing,NaNmissing。删除包含missing我可以使用的行dropmissing。有什么方法可以处理NaNnothing吗?

示例 df:

? Row ? x       ? y    ?
?     ? Union…? ? Char ?
????????????????????????
? 1   ? 1.0     ? 'a'  ?
? 2   ? missing ? 'b'  ?
? 3   ? 3.0     ? 'c'  ?
? 4   ?         ? 'd'  ?
? 5   ? 5.0     ? 'e'  ?
? 6   ? NaN     ? 'f'  ?
Run Code Online (Sandbox Code Playgroud)

预期输出:

? Row ? x   ? y    ?
?     ? Any ? Char ?
????????????????????
? 1   ? 1.0 ? 'a'  ?
? 2   ? 3.0 ? 'c'  ?
? 3   ? 5.0 ? 'e'  ?
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试过的,根据我对 Julia 的了解,我尝试了这个,

df.x = replace(df.x, NaN=>"something", missing=>"something", nothing=>"something")
print(df[df."x".!="something", :])
Run Code Online (Sandbox Code Playgroud)

我的代码按预期工作。我觉得这是解决这个问题的无效方法。是否有任何单独的方法来处理空和 NaN?

Bog*_*ski 5

你可以这样做:

julia> df = DataFrame(x=[1,missing,3,nothing,5,NaN], y='a':'f')
6×2 DataFrame
? Row ? x       ? y    ?
?     ? Union…? ? Char ?
????????????????????????
? 1   ? 1.0     ? 'a'  ?
? 2   ? missing ? 'b'  ?
? 3   ? 3.0     ? 'c'  ?
? 4   ?         ? 'd'  ?
? 5   ? 5.0     ? 'e'  ?
? 6   ? NaN     ? 'f'  ?

julia> filter(:x => x -> !any(f -> f(x), (ismissing, isnothing, isnan)), df)
3×2 DataFrame
? Row ? x       ? y    ?
?     ? Union…? ? Char ?
????????????????????????
? 1   ? 1.0     ? 'a'  ?
? 2   ? 3.0     ? 'c'  ?
? 3   ? 5.0     ? 'e'  ?
Run Code Online (Sandbox Code Playgroud)

请注意,这里检查的顺序很重要,isnan应该放在最后,否则此检查将失败 for missingor nothingvalue。

你也可以更直接地写成:

julia> filter(:x => x -> !(ismissing(x) || isnothing(x) || isnan(x)), df)
3×2 DataFrame
? Row ? x       ? y    ?
?     ? Union…? ? Char ?
????????????????????????
? 1   ? 1.0     ? 'a'  ?
? 2   ? 3.0     ? 'c'  ?
? 3   ? 5.0     ? 'e'  ?
Run Code Online (Sandbox Code Playgroud)

但我觉得这个例子any更具可扩展性(然后您可以存储谓词列表以检查变量)。

missingDataFrames.jl 中仅提供删除函数的原因是,这通常被认为是有效但可取的删除数据科学管道中的值。

通常在 Julia 中,当您看到nothingNaN您可能想要以不同的方式处理它们时missing,它们很可能表示数据或数据处理中存在错误(而不是missing表示数据未收集的信号)。