How to one-hot encode a table column in DolphinDB?

Viewed 28

I’d like to perform one-hot encoding on the industryCode column and preserve all other columns in the following table.

t = table(2022.08.01 2022.08.02 2022.08.03 as date, 000001.SZ000002.SZ000003.SZ as windCode, 110111021103 as industryCode)

enter image description here

After the conversion, the table should look like:

enter image description here

1 Answers

Based on your requests, there are two ways to solve this.

The table:

t = table(2022.08.01 2022.08.02 2022.08.03 as date, `000001.SZ`000002.SZ`000003.SZ as windCode, `1101`1102`1103 as industryCode)

Solution #1:

Use built-in function oneHot(obj, encodingColumns)

oneHot(t, ['industryCode'])

enter image description here

Worth mentioning, with the method above, you can one hot encode multiple columns all at once.

oneHot(t, ['industryCode','windCode'])

enter image description here

Solution #2:

Use SQL query

res = select iif(isNull(industryCode), 0, 1) from t pivot by date, windCode, industryCode;
nullFill!(res, 0);

enter image description here

I’d recommend solution #1 for its much simpler implementation, yet supporting multiple columns.

Related