# One Hot Encode columns with categorical data

I have a couple of survey datasets that I am loading into Mathematica to do behavioral clustering.

I have columns of responses (Strings) where the users was given a fixed set of responses. The surveys are really high dimensions so I can't manually go through every question type and assign a value to each string in each one of these columns.

Is there a way I could encode the responses into numbers and do this for each column that has categorical responses like this?

For each column that looks like this food["apple","pear","apple","orange","pizza","pizza"] and convert it to food[1,2,1,3,4,4]

• see ArrayComponents. – Kuba Oct 24 '17 at 16:45

food = {{"apple", "pizza"}, {"pear", "pizza"}, {"apple",
"orange"}, {"orange", "apple"}, {"pizza", "pear"}, {"pizza",
"apple"}};


fe = FeatureExtraction[
food,
{1 -> "IntegerVector", 2 -> "IndicatorVector"},
FeatureTypes -> <|{1, 2} -> "Nominal"|>
];

fe@food // TableForm


fe@{"unknown_food", "unknown_food"}


{0, 0., 0., 0., 0.}

Try creating a range and and a rule to send the arguments to the range values.

food["apple","pear","apple","orange","pizza","pizza"]/.
food[args___]:>With[{un=Union@{args}},With[{rng=Range@Length@un},

NetEncoder is perfect for this:
encode[list_]:= NetEncoder[{"Class", DeleteDuplicates[list]}][list]