Julia dataframe directly access row

In Julia DataFrames it is possible to directly access a column :col of a dataframe df by writing df[!, :col]. Is it a similar fast way to directly access a row? I know I can do df[2, :] to get a copy of row 2, but I don't want a copy since I want to change the content of the row.

Cheers Sigurd

Upvotes: 7

Views: 7126

Answers (1)

Cameron Bieganek
Cameron Bieganek

Reputation: 7654

Selecting a single row from a data frame returns a DataFrameRow, which is a view of the row in the original data frame. So any changes you make to the DataFrameRow will be reflected in the original data frame:

julia> using DataFrames

julia> df = DataFrame(a=1:3, b=4:6)
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 5     │
│ 3   │ 3     │ 6     │

julia> dfr = df[2, :]
DataFrameRow
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 2   │ 2     │ 5     │

julia> dfr.b = 100
100

julia> df
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 100   │
│ 3   │ 3     │ 6     │

Of course, if you just want to change the values of a few entries in a row, you can do that directly without having to first create a DataFrameRow:

julia> df = DataFrame(a=1:3, b=4:6)
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 5     │
│ 3   │ 3     │ 6     │

julia> df[2, :] = [101, 102]
2-element Array{Int64,1}:
 101
 102

julia> df
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 101   │ 102   │
│ 3   │ 3     │ 6     │

Upvotes: 8

Related Questions