Clear Filters
Clear Filters

Not possible to one hot encode in a timetable column

8 views (last 30 days)
I am trying to do a simple one hot encoding in one of the column of a time table but it's becoming an impossible task.
I have tried to convert that column to a table and even to an array buty nothing works.
months = timetable2table(df_tmp(:, {'month'}), 'ConvertRowTimes', false);
nehotencode(months);
The error states: "First argument must contain a single label for each observation."
It shouldn't be that difficult but I do not manage to convert a single column to a one hot enconding.
Thanks in advance,
Rafa

Answers (1)

Ayush Modi
Ayush Modi on 19 Jun 2024
Edited: Ayush Modi on 19 Jun 2024
Hi Rafael,
I am assuming you are referring to onehotencode function in MATLAB.
The error is because onehotencode function expects a table of categorical data. Otherwise, a class for each variable needs to be provided to the function.
Here is the example code to demonstrate how to achieve the same with the categorical data:
% I am using sample data for the example.
dt = datetime(2021, 1, 1) + calmonths(0:11); % Monthly data for one year
months = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'};
df_table = timetable(dt', months', 'VariableNames', {'Months'});
disp(df_table);
Time Months ___________ _______ 01-Jan-2021 {'Jan'} 01-Feb-2021 {'Feb'} 01-Mar-2021 {'Mar'} 01-Apr-2021 {'Apr'} 01-May-2021 {'May'} 01-Jun-2021 {'Jun'} 01-Jul-2021 {'Jul'} 01-Aug-2021 {'Aug'} 01-Sep-2021 {'Sep'} 01-Oct-2021 {'Oct'} 01-Nov-2021 {'Nov'} 01-Dec-2021 {'Dec'}
% Converting the data into categorical data
categoricalData = categorical(df_table.Months)
categoricalData = 12x1 categorical array
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
% Converting to a table
tblA = table(categoricalData)
tblA = 12x1 table
categoricalData _______________ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
encodedData = onehotencode(tblA);
disp(encodedData);
Apr Aug Dec Feb Jan Jul Jun Mar May Nov Oct Sep ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0
Refer to the following MathWorks documentation for more information on:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!