udibehar
(Ehud Behar)
1
I have the following nested dataset:
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:
Doing
ds = ds["x", All, <|#, "new" -> f[#col1]|> &]
adds the column but removes information about the “y” key.
eric3
(Eric Rimbey)
2
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]]
You were quite close!, Try:
ds[All, All, <|#, "col3" -> f[#col1]|> &]
udibehar
(Ehud Behar)
4
Thanks, but this appends a column col3 to both key "x" and key "y":
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".
gdelfino
(Gustavo Delfino)
5
This is one way:
ds // MapAt[Append[#, "col3" -> f[#col1]] &, {"x", All}]