使用多个条件选择数据框的子集行

12

我想选择一个数据框的子集,该子集满足多个行上的多个条件。 我知道我可以依次执行此操作 - 首先选择与第一个条件匹配的子集,然后再选择那些符合第二个条件的部分,等等,但似乎应该能够在单个步骤中完成。 以下内容似乎应该有效,但实际上并不起作用。 显然,在其他语言的DataFrame实现中,它可以这样工作。 有什么想法吗?

using DataFrames
df = DataFrame()
df[:A]=[ 1, 3, 4, 7, 9]
df[:B]=[ "a", "c", "c", "D", "c"]
df[(df[:A].<5)&&(df[:B].=="c"),:] 

type: non-boolean (DataArray{Bool,1}) used in boolean context
while loading In[18], in expression starting on line 5
2个回答

16

这是一个Julia的问题,而不是DataFrame的问题:你需要使用&而不是&&。例如:

julia> [true, true] && [false, true]
ERROR: TypeError: non-boolean (Array{Bool,1}) used in boolean context

julia> [true, true] & [false, true]
2-element Array{Bool,1}:
 false
  true

julia> df[(df[:A].<5)&(df[:B].=="c"),:]
2x2 DataFrames.DataFrame
| Row | A | B   |
|-----|---|-----|
| 1   | 3 | "c" |
| 2   | 4 | "c" |

顺便提一下,在Python的pandas中,这个方式也是有效的:

>>> df[(df.A < 5) & (df.B == "c")]
   A  B
1  3  c
2  4  c

哎呀,我应该自己注意到那个问题 -- 我甚至查看了相关的pandas问题, 但是习惯性地打了 “&&” … 谢谢! - ARM
5
这个有改变吗?尝试类似的东西时,我收到了错误警告:“WARNING: a::DataArray{$(Expr(:<:, :Integer))} & b::DataArray{$(Expr(:<:, :Integer))} is deprecated, use &.(a, b) instead.” - jwimberley
1
在现代的Julia(我的情况是1.5.3),需要对所提出的解决方案进行小修改:df[(df[:A] .< 5) .& (df[:B] .== "c"), :] - Anton Degterev
更新答案:https://discourse.julialang.org/t/selecting-rows-from-a-data-frame-using-multiple-conditions/73282 - Smithey
1
在现代的Dataframes.jl中,表达式“df[:A]”不再有效,而需要使用表达式“df.A”或“df[:, :A]”或“df[!, :A]”。 - Anton Degterev
在(如果我没记错的话)Julia 1.7中,他们使&&可广播,因此.&&应该按预期工作。 - BallpointBen

3

我现在遇到了与https://stackoverflow.com/users/5526072/jwimberley相同的问题,这是在升级到Julia 0.6并使用数据框v0.10.1后发生的。

更新:我做出了以下更改来解决问题:

r[(r[:l] .== l) & (r[:w] .== w), :] # julia 0.5

r[.&(r[:l] .== l, r[:w] .== w), :] # julia 0.6

但是当链条很长时,这会变得非常缓慢(时间与链条长度成指数关系),所以现在也许查询是更好的方法:

# r is a dataframe
using Query
q1 = @from i in r begin
    @where i.l == l && i.w == w && i.nl == nl && i.lt == lt && 
    i.vz == vz && i.vw == vw && i.vδ == vδ && 
    i.ζx == ζx && i.ζy == ζy && i.ζδx == ζδx
    @select {absu=i.absu, i.dBU}
    @collect DataFrame
end

例如,这很快。它在数据框文档中提到。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接