logo

How to Add a Column Filled with the Same Value to a Julia DataFrame 📂Julia

How to Add a Column Filled with the Same Value to a Julia DataFrame

Code

Fundamentally, this is similar to the method to add a new column, but initialization can be easily performed without creating a separate column by applying broadcasting to the assignment operation = using .=.

julia> df = DataFrame(rand(3, 4), :auto)
3×4 DataFrame
 Row │ x1        x2        x3        x4       
     │ Float64   Float64   Float64   Float64  
─────┼────────────────────────────────────────
   1 │ 0.985664  0.243474  0.578638  0.391492
   2 │ 0.695083  0.631775  0.732797  0.94087
   3 │ 0.105434  0.280295  0.158923  0.681144

julia> df[!, :new] .= 0
3-element Vector{Int64}:
 0
 0
 0

julia> df
3×5 DataFrame
 Row │ x1        x2        x3        x4        new   
     │ Float64   Float64   Float64   Float64   Int64 
─────┼───────────────────────────────────────────────
   1 │ 0.985664  0.243474  0.578638  0.391492      0
   2 │ 0.695083  0.631775  0.732797  0.94087       0
   3 │ 0.105434  0.280295  0.158923  0.681144      0

Complete Code

using DataFrames

df = DataFrame(rand(3, 4), :auto)
df[!, :new] .= 0

Environment

  • OS: Windows
  • julia: v1.11.1