Home > Enterprise >  Julia - How to find the specific data in the Julia DataFrame by conditions and change it?
Julia - How to find the specific data in the Julia DataFrame by conditions and change it?

Time:11-17

I have a DataFrame that has the following structure, for example:

show(q)
2×5 DataFrame
 Row │ state   left     right    up       down    
     │ Any     Float64  Float64  Float64  Float64
─────┼────────────────────────────────────────────
   1 │ (1, 1)      0.0      0.0      0.0      0.0
   2 │ (2, 2)      0.0      0.0      0.0      0.0

where I use the column state as an index column that takes tuples as indexes. I want to access the data using the index such as q[q.state .== (1,1), 'down'], how can I do that?

Furthermore, when I use this command q[q.state .== (1,1), :] to access the row of the corresponding state, it returns me an empty DataFrame:

0×5 DataFrame
 Row │ state  left     right    up       down    
     │ Any    Float64  Float64  Float64  Float64
─────┴───────────────────────────────────────────

Why is that?

CodePudding user response:

First, the mistake you make is when you write q.state .== (1,1), as it produces:

julia> q.state .== (1,1)
2-element BitVector:
 0
 0

because (1,1) is broadcasted over.

You need to write:

julia> q.state .== Ref((1,1))
2-element BitVector:
 1
 0

to treat (1,1) as scalar.

Now you have:

julia> q[q.state .== Ref((1,1)), :]
1×5 DataFrame
 Row │ state   left  right  up   down
     │ Any     Any   Any    Any  Any
─────┼────────────────────────────────
   1 │ (1, 1)  0.0   0.0    0.0  0.0

If you want to access a single cell of a data frame, with lookup write:

julia> q[findfirst(==((1,1)), q.state), :down]
0.0

or if you are more prudent (and make sure you have only one match):

julia> q[only(findall(==((1,1)), q.state)), :down]
0.0
  • Related