Message Boards Message Boards

0
|
488 Views
|
4 Replies
|
6 Total Likes
View groups...
Share
Share this post:

Append a column to a nested dataset

Posted 3 months ago

I have the following nested dataset:

enter image description here

ds = Dataset[
  <|"x" ->
    {<|"col1" -> 4.2, "col2" -> 2.5|>, <|"col1" -> 1.6, 
      "col2" -> 7.4|>, <|"col1" -> 7.1, "col2" -> 3.6|>}
   ,
   "y" ->
    {<|"col1" -> 9.1, "col2" -> 2.8|>, <|"col1" -> 2.7, 
      "col2" -> 5.4|>, <|"col1" -> 5.3, "col2" -> 0.6|>}
   |>
  ]

How can I append a column col3 to the x sub-dataset, so that col3=f[col1], as below:

enter image description here

Doing

ds = ds["x", All, <|#, "new" -> f[#col1]|> &]

adds the column but removes information about the "y" key.

POSTED BY: Ehud Behar
4 Replies
Posted 3 months ago

This is one way:

ds // MapAt[Append[#, "col3" -> f[#col1]] &, {"x", All}]
POSTED BY: Gustavo Delfino

You were quite close!, Try:

ds[All, All, <|#, "col3" -> f[#col1]|> &]
POSTED BY: Henrik Schachner
Posted 3 months ago

Thanks, but this appends a column col3 to both key "x" and key "y":

enter image description here

I want to apply f[#col1] on the values of key "x" and keep my self the option of applying g[#col1] on the values of key "y".

POSTED BY: Ehud Behar
Posted 3 months ago

Here's one approach that uses a purpose-built function to decide how to add the column.

AddColumn["x", as_] := "x" -> Map[Append[#, "new" -> f[#col1]] &, as];
AddColumn[key_, as_] := key -> as;

ds[KeyValueMap[AddColumn]/*Apply[Association]]

Or, to re-assign ds

ds = ds[KeyValueMap[AddColumn]/*Apply[Association]]
POSTED BY: Eric Rimbey
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract