6
$\begingroup$

What I am trying to do is to add an id column at the left side of my data set.

This is the data set I am working with. I Have three columns and I want to add a new column on the left side with the column tag ID with the following values: Id={1,2,3,4,5,6}.

Dataset@ { <|"Team name" -> "Chealse", "GF" -> 23, "GA" -> 12|>, <|"Team name" -> "Arsenal", "GF" -> 30, "GA" -> 13|>, <|"Team name" -> "Burnley", "GF" -> 33, "GA" -> 15|>, <|"Team name" -> "Everton", "GF" -> 53, "GA" -> 11|>, <|"Team name" -> "Watford", "GF" -> 45, "GA" -> 9|>, <|"Team name" -> "Brighton", "GF" -> 24, "GA" -> 7|> } 
$\endgroup$
2
  • 2
    $\begingroup$ see how-can-i-add-a-column-into-a-existing-dataset $\endgroup$ Commented May 31, 2020 at 5:12
  • $\begingroup$ If your dataset is ds then n = 1; ds = ds[All, Prepend[#, "ID" -> n++] &] $\endgroup$ Commented May 31, 2020 at 5:55

2 Answers 2

7
$\begingroup$
Join[Dataset[Association /@ Thread["ID" -> Id]], ds, 2] 

enter image description here

Also

MapIndexed[Prepend[#, "ID" -> #2[[1]]] &, ds] 

enter image description here

$\endgroup$
3
  • $\begingroup$ It worked fine, but I don´t understand the 2 on the Join function. $\endgroup$ Commented May 31, 2020 at 22:33
  • 2
    $\begingroup$ @LasDes, the third argument of Join specifies that the elements at Level 2 of the objects in the first and second argument are to be joined. Try, for example, Join[{{a}, {b}, {c}}, {{1}, {2}, {3}}] and Join[{{a}, {b}, {c}}, {{1}, {2}, {3}}, 2] $\endgroup$ Commented May 31, 2020 at 22:37
  • $\begingroup$ I can see now why, thanks. $\endgroup$ Commented May 31, 2020 at 22:42
2
$\begingroup$

Another way

ds[MapIndexed[<|"ID" -> First@#2, #|> &]] 

enter image description here

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.