7
$\begingroup$

Form the documentation of Dataset:

    dataset = Dataset[{
   <|"a" -> 1, "b" -> "x", "c" -> {1}|>,
   <|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,
   <|"a" -> 3, "b" -> "z", "c" -> {3}|>,
   <|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>,
   <|"a" -> 5, "b" -> "y", "c" -> {5, 6, 7}|>,
   <|"a" -> 6, "b" -> "z", "c" -> {}|>}]

gives a Dataset with columns "a", "b" and "c". To rename a column in a Dataset one uses the syntax

 dataset[All,<|"New"->"old"|>]

where "old" is the old column name and "New" is the new one. Here (also from the documentation):

dataset[All, <|"A" -> "a", "B" -> "b", "C" -> "c"|>]

and one gets the new Dataset with columns "A", "B" and "C". I wonder why this is in this way and not:

 dataset[All,<|"old"->"New"|>]

Can one give me a hint?

$\endgroup$
1
  • 3
    $\begingroup$ The "old" is implicitly #["old"]. With that in mind, #["old"]->"New" is not what we want; "New"->#["old"] is. $\endgroup$
    – b3m2a1
    Commented Dec 25, 2017 at 22:34

2 Answers 2

7
$\begingroup$

Just came across the same problem and find the following might be a sensible way:

dataset[All,KeyMap[Replace["old" -> "New"]]]

This approach essentially conducts the idea of OP and reserves the names of other columns.

BTW, I find the way suggested by the official documentation to rename columns (i.e., using Association as the operator) seems a bit tedious as unconnected columns are also involved to construct a new Association.

$\endgroup$
5
$\begingroup$

The easiest way to think about the short-hand query syntax is to turn to the documentation of Query, where we find that Query[All,f] will apply the function f to every row. So Query[All, <|"aaa" -> #"a"|> &] would be the natural way to write a query. The way you wrote it (i.e., Query[All, <|"aaa" -> "a"|> ]) is allowed as a more compact expression of the same query.

(Btw, this is not really "renaming", since it produces a new dataset.)

$\endgroup$
3
  • $\begingroup$ But... I do not see how this answers the main question: why "New"->"old" instead of "old"->"New"? $\endgroup$ Commented Dec 25, 2017 at 20:04
  • 1
    $\begingroup$ @AlexeyPopkov Again, the reason is that you are effectively using a shorthand for a function definition, where this kind of function allows you to extract values from an association by using the keys. Again, this is really not renaming: it is effectively creating a new dataset by mapping this function across the rows of the old dataset. Try it that way to see: <|"aaa" -> #"a"|> & /@ dataset. You can use any function you want to, of course, but try to think of one that would use the notation you suggest... $\endgroup$
    – Alan
    Commented Dec 26, 2017 at 14:53
  • $\begingroup$ Thanks, now I got it! $\endgroup$ Commented Dec 26, 2017 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.