Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a column with a constant value to a DataFrame

How can I add a column with a constant value to a DataFrame?

E.g. I have the following DataFrame:

using DataFrames

df = DataFrame(x = 1:10, y = 'a':'j')

And I would like to add a new variable z with constant value 1 and obtain:

10×3 DataFrame
 Row │ x      y     z     
     │ Int64  Char  Int64
─────┼────────────────────
   1 │     1  a         1
   2 │     2  b         1
   3 │     3  c         1
   4 │     4  d         1
   5 │     5  e         1
   6 │     6  f         1
   7 │     7  g         1
   8 │     8  h         1
   9 │     9  i         1
  10 │    10  j         1
like image 427
Josep Espasa Avatar asked Oct 24 '25 04:10

Josep Espasa


2 Answers

To create such column:

df = DataFrame(x = 1:10, y = 'a':'j', d = 1)

To append such column to the existing DataFrame, you need broadcasting:

df.e .= 1

or

df[:, "f"] .= 1

like image 172
Likan Zhan Avatar answered Oct 25 '25 21:10

Likan Zhan


A more general alternative is:

julia> insertcols!(df, :z => 1)
10×3 DataFrame
 Row │ x      y     z
     │ Int64  Char  Int64
─────┼────────────────────
   1 │     1  a         1
   2 │     2  b         1
   3 │     3  c         1
   4 │     4  d         1
   5 │     5  e         1
   6 │     6  f         1
   7 │     7  g         1
   8 │     8  h         1
   9 │     9  i         1
  10 │    10  j         1

which by default does the same, but it additionally:

  1. allows you to specify the location of the new column;
  2. by default makes sure that you do not accidentally overwrite an existing column
like image 25
Bogumił Kamiński Avatar answered Oct 25 '25 22:10

Bogumił Kamiński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!