Can't seem to create a new column with the right type

2 visualizaciones (últimos 30 días)
Quoc Huy
Quoc Huy el 10 de Mayo de 2023
Comentada: Peter Perkins el 5 de Jun. de 2023
Hello there, I'm learning matlab and have some problems relating to tables. What i'm doing now is to change the type and name of columns through the method of creating a new column and removing the old one. this works pretty well expect for one column that can't change from number to categorical type. What do i need to adjust to make it right? Thanks
% Import may2008.csv
tempTable = readtable('/MATLAB Drive/may2008.csv');
% Rename and convert columns
tempTable.station_id = categorical(tempTable.sid);
tempTable = removevars(tempTable, 'sid');
tempTable.station_name = categorical(tempTable.snm);
tempTable = removevars(tempTable, 'snm');
tempTable.city = categorical(tempTable.city);
tempTable.province = categaorical(tempTable.prov);
tempTable = removevars(tempTable, 'prov');
tempTable.date_time = datetime(tempTable.datetime, 'InputFormat', 'dd MMMM y H:mm:ss');
tempTable = removevars(tempTable, 'datetime');
data_may_2008 = tempTable(:, [19 20 1 21 22 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18])
writetable(data_may_2008, '/MATLAB Drive/kajefhgakejlfghasdfkjlghasdfkljghasdg.csv');

Respuestas (1)

dpb
dpb el 10 de Mayo de 2023
We don't have the input file and you neglected to tell us even what variable you couldn't covert so not much can be said about fixing such an issue...always best to attach the actual input file and certainly always provide all the error message text and context.
That said, use the features built into the MATLAB table -- the above could be written as
% Import may2008.csv
tempTable = readtable('/MATLAB Drive/may2008.csv');
% Rename variables...
tempTable=renamevars(tempTable,{'sid','snm','prov','datetime'}, ...
{'station_id','station_name','province','date_time'});
% convert types
tempTable=convertvars({'station_id','station_name','province'},'categorical');
tempTable.date_time = datetime(tempTable.datetime, 'InputFormat', 'dd MMMM y H:mm:ss');
data_may_2008 = tempTable(:, [19 20 1 21 22 2:18])
writetable(data_may_2008, '/MATLAB Drive/kajefhgakejlfghasdfkjlghasdfkljghasdg.csv');
  1 comentario
Peter Perkins
Peter Perkins el 5 de Jun. de 2023
As dpb says, any answer is just guessing at this point, but with "why can't I convert the type of a variable in a table?", usually this is the problem. This
tempTable.station_id = categorical(tempTable.sid);
completely overwrites that variable, including chaging the type.
This
tempTable(:,"station_id") = categorical(tempTable.sid);
writes into the variable, and therefor cannot change the type.

Iniciar sesión para comentar.

Categorías

Más información sobre Time Series Objects en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by