dataframe - julia DataFrame 选择属于一组的一列的基于行的值

标签 dataframe select julia rows

在 Julia 中使用 DataFrame,我想根据列中的值选择行。

用下面的例子

using DataFrames, DataFramesMeta
DT = DataFrame(ID = [1, 1, 2,2,3,3, 4,4], x1 = rand(8))

我想提取 ID 取值为 1 和 4 的行。
目前,我提出了这个解决方案。
@where(DT, findall(x -> (x==4 || x==1), DT.ID))

当仅使用两个值时,它是可管理的。

但是,我想让它适用于要选择的 ID 具有多行和大量值的情况。因此,如果我需要写下所有要选择的值,这个解决方案是不切实际的

有什么更好的解决方案可以使这个选择通用?

达米安

最佳答案

这是一种使用标准 DataFrames.jl 索引并使用 @where 的方法。来自 DataFramesMeta.jl:

julia> DT
8×2 DataFrame
│ Row │ ID    │ x1        │
│     │ Int64 │ Float64   │
├─────┼───────┼───────────┤
│ 1   │ 1     │ 0.433397  │
│ 2   │ 1     │ 0.963775  │
│ 3   │ 2     │ 0.365919  │
│ 4   │ 2     │ 0.325169  │
│ 5   │ 3     │ 0.0495252 │
│ 6   │ 3     │ 0.637568  │
│ 7   │ 4     │ 0.391051  │
│ 8   │ 4     │ 0.436209  │

julia> DT[in([1,4]).(DT.ID), :]
4×2 DataFrame
│ Row │ ID    │ x1       │
│     │ Int64 │ Float64  │
├─────┼───────┼──────────┤
│ 1   │ 1     │ 0.433397 │
│ 2   │ 1     │ 0.963775 │
│ 3   │ 4     │ 0.391051 │
│ 4   │ 4     │ 0.436209 │

julia> @where(DT, in([1,4]).(:ID))
4×2 DataFrame
│ Row │ ID    │ x1       │
│     │ Int64 │ Float64  │
├─────┼───────┼──────────┤
│ 1   │ 1     │ 0.433397 │
│ 2   │ 1     │ 0.963775 │
│ 3   │ 4     │ 0.391051 │
│ 4   │ 4     │ 0.436209 │

在非性能关键代码中,您还可以使用 filter ,这是 - 至少对我来说更容易消化(但它有一个缺点,它比上面讨论的方法慢):
julia> filter(row -> row.ID in [1,4], DT)
4×2 DataFrame
│ Row │ ID    │ x1       │
│     │ Int64 │ Float64  │
├─────┼───────┼──────────┤
│ 1   │ 1     │ 0.433397 │
│ 2   │ 1     │ 0.963775 │
│ 3   │ 4     │ 0.391051 │
│ 4   │ 4     │ 0.436209 │

请注意,在您在问题中提到的方法中,您可以省略 DT前面ID像这样:
julia> @where(DT, findall(x -> (x==4 || x==1), :ID))
4×2 DataFrame
│ Row │ ID    │ x1       │
│     │ Int64 │ Float64  │
├─────┼───────┼──────────┤
│ 1   │ 1     │ 0.433397 │
│ 2   │ 1     │ 0.963775 │
│ 3   │ 4     │ 0.391051 │
│ 4   │ 4     │ 0.436209 │

(这是 DataFramesMeta.jl 的一个优点,它知道您要引用的 DataFrame 的上下文)

关于dataframe - julia DataFrame 选择属于一组的一列的基于行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58220143/

相关文章:

Python: Pandas 中的数据框操作和聚合

julia - 如何在 Julia 中将数组转换为矩阵

python - 数据框的填充列

python - 创建列的滚动总和,该列在 python pandas 中按周滚动分组

python - 使用 pandas 将 Excel 日期格式 (DDDDD.tttt) 的列转换为日期时间

javascript - 使用 javascript 在 HTML 选择上添加事件

sockets - 调用选择标准 ML 时出现类型错误

mysql - 如何在3个表之间选择sql行,2个表应该有给定值,但1个表不应该有值

shell - 将两个字符串传递给 Julia 中的外部实用程序 diff

asynchronous - 在 Julia 中使用 @sync @async 的简单并行性