如何根据指定列中的值过滤 Julia Array 中的行?

Luk*_*uke 6 filter julia

我在文本文件中有这样的数据:

CLASS     col2    col3    ...
1         ...     ...     ...
1         ...     ...     ...
2         ...     ...     ...
2         ...     ...     ...
2         ...     ...     ...
Run Code Online (Sandbox Code Playgroud)

我使用以下代码加载它们:

data = readdlm("file.txt")[2:end, :] # without header line
Run Code Online (Sandbox Code Playgroud)

现在我只想从第 1 类中获取包含行的数组。

(如果有帮助,可以使用其他一些函数加载数据。)

Mat*_* B. 7

逻辑索引是对数组进行过滤的直接方法:

data[data[:,1] .== 1, :]
Run Code Online (Sandbox Code Playgroud)

但是,如果您将文件作为数据框读入,您将有更多可用选项,并且它会跟踪您的标题:

julia> using DataFrames
julia> df = readtable("file.txt", separator=' ')
5×4 DataFrames.DataFrame
? Row ? CLASS ? col2  ? col3  ? _     ?
???????????????????????????????????????
? 1   ? 1     ? "..." ? "..." ? "..." ?
? 2   ? 1     ? "..." ? "..." ? "..." ?
? 3   ? 2     ? "..." ? "..." ? "..." ?
? 4   ? 2     ? "..." ? "..." ? "..." ?
? 5   ? 2     ? "..." ? "..." ? "..." ?

julia> df[df[:CLASS] .== 1, :] # Refer to the column by its header name
2×4 DataFrames.DataFrame
? Row ? CLASS ? col2  ? col3  ? _     ?
???????????????????????????????????????
? 1   ? 1     ? "..." ? "..." ? "..." ?
? 2   ? 1     ? "..." ? "..." ? "..." ?
Run Code Online (Sandbox Code Playgroud)

DataFramesMeta 包还有更多可用的工具,旨在使这更简单(以及其他正在积极开发的包)。你可以使用它的@where宏来做 SQL 风格的过滤:

julia> using DataFramesMeta
julia> @where(df, :CLASS .== 1)
2×4 DataFrames.DataFrame
? Row ? CLASS ? col2  ? col3  ? _     ?
???????????????????????????????????????
? 1   ? 1     ? "..." ? "..." ? "..." ?
? 2   ? 1     ? "..." ? "..." ? "..." ?
Run Code Online (Sandbox Code Playgroud)