JKHA
JKHA

Reputation: 1896

Julia - DataFrames Insert a Row at Specific index in Julia 1.1

How can I insert a row in a dataframe in Julia at a specific index ? (Julia version 1.1)

I have found this related question. However, the code given in the answer isn't working anymore in Julia 1.1

I know how to push! a row into a dataframe or concatenate two dataframes, but what about inserting at a specific index ?

It also doesn't seem to be explained in Julia DataFrames documentation.

Upvotes: 4

Views: 622

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69879

This is a non-standard operation. The recommendation given there is still valid, so:

df = DataFrame(x = [1,2,3], y = ["a", "b", "c"])
foreach((v,n) -> insert!(df[n], 2, v), [4, "d"], names(df))

works. A shorter version to write it under Julia 1.0 would be:

insert!.(eachcol(df, false), 2, [4, "d"])

(the need to add false as a second argument will not be needed in the future as we are in the deprecation period now)

The difference is that getproperty method can be overloaded since Julia 1.0 so df.columns does not work.

I have also updated the other answer, so you can close this question if you prefer.

EDIT

The instructions above are no longer valid (unless you use very old DataFrames.jl version).

In DataFrames.jl 1.4 use insert!, push!, or pushfirst! functions depending on where you want to add the row:

julia> using DataFrames

julia> df = DataFrame(x = [1,2,3], y = ["a", "b", "c"])
3×2 DataFrame
 Row │ x      y
     │ Int64  String
─────┼───────────────
   1 │     1  a
   2 │     2  b
   3 │     3  c

julia> insert!(df, 2, (100, "new line"))
4×2 DataFrame
 Row │ x      y
     │ Int64  String
─────┼─────────────────
   1 │     1  a
   2 │   100  new line
   3 │     2  b
   4 │     3  c

julia> push!(df, (200, "last line"))
5×2 DataFrame
 Row │ x      y
     │ Int64  String
─────┼──────────────────
   1 │     1  a
   2 │   100  new line
   3 │     2  b
   4 │     3  c
   5 │   200  last line

julia> pushfirst!(df, (300, "first line"))
6×2 DataFrame
 Row │ x      y
     │ Int64  String
─────┼───────────────────
   1 │   300  first line
   2 │     1  a
   3 │   100  new line
   4 │     2  b
   5 │     3  c
   6 │   200  last line

Upvotes: 4

Related Questions