3
$\begingroup$

I've got a dataset with 100+ various columns. I want to change e.g. the values 0 and 1 in the first column with "male" and "female". In the second column i'd like to change the 0 and 1 with e.g. "alive" or "dead".

When applying following code, it does not produce the desired output since the values don't get overwritten in my dataset called data even though my first column has the correct header "Gender" with all the Associations. How can it be achieved?

data[ReplaceAll[{1 -> "Male", 0 -> "Female"}],"Gender"];
$\endgroup$
6
$\begingroup$

For discussion, let us consider the following dataset:

data = Dataset @ Table[
  <|"Gender" -> RandomInteger[1], "Status" -> RandomInteger[1], "Data" -> RandomReal[]|>
, 4
]

dataset screenshot

A query will not update a dataset in place. Rather, it generates a new dataset containing the result. So, using the query from the question (without the trailing semicolon which suppresses the output) we see:

data[ReplaceAll[{1 -> "Male", 0 -> "Female"}], "Gender"]

dataset screenshot

This shows the correctly altered Gender column. But only that column. This is because the "Gender" operator projects out the column with that name:

data[All, "Gender"]

dataset screenshot

Note that the original dataset is left untouched.

If we wish to generate a new dataset with transformed Gender and Status columns, we must apply query operators to only those columns. We can do this by name:

data[
  All
, { "Gender" -> Replace[{1 -> "Male", 0 -> "Female"}]
  , "Status" -> Replace[{1 -> "Alive", 0 -> "Dead"}]
  }
]

dataset screenshot

... or by column index (1 = Gender, 2 = Status):

data[
  All
, { 1 -> Replace[{1 -> "Male", 0 -> "Female"}]
  , 2 -> Replace[{1 -> "Alive", 0 -> "Dead"}]
  }
]

dataset screenshot

In both cases, a new complete dataset is returned with the original remaining untouched.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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