logo

How to Add a New Column to the First Column in a Julia DataFrame 📂Julia

How to Add a New Column to the First Column in a Julia DataFrame

Code

Adding a new column itself is not particularly difficult, but it can be tricky to add it at a specific position.

insertcols!

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> new = [-2, -1, 0]
3-element Vector{Int64}:
 -2
 -1
  0

To add a new column new as the first column to the given DataFrame df as shown above, you can use the insertcols! function1.

julia> insertcols!(df, 1, :c => new)
3×3 DataFrame
 Row │ c      a      b     
     │ Int64  Int64  Int64 
─────┼─────────────────────
   1 │    -2      1      4
   2 │    -1      2      5
   3 │     0      3      6

Complete Code

using DataFrames

df = DataFrame(a = 1:3, b = 4:6)
new = [-2, -1, 0]
insertcols!(df, 1, :c => new)

Environment

  • OS: Windows
  • julia: v1.11.3