How can I get MATLAB to preserve column names as variables when importing a csv file to timetable?
147 ビュー (過去 30 日間)
古いコメントを表示
Hello,
I can't seem to get MATLAB to import a csv file and preserve the column names as variables. The variable names come back as Var1, Var2, etc. Here's one of the approaches I've tried:
opts = detectImportOptions('test.csv',"VariableNamingRule","preserve");
test= readtimetable('test.csv', opts);
I've also left off the options qualifiers, but to no avail. The variable names still come back as Var1, Var2, etc.
Interestingly, the variable names are preserved if I use the Import wizard, but this is not a long-term solution. I have the same problem if readtable is used instead of readtimetable.
Any assistance greatly appreciated! Thanks for reading-
Nina
12 件のコメント
採用された回答
その他の回答 (2 件)
Star Strider
2023 年 10 月 24 日
編集済み: Star Strider
2023 年 10 月 25 日
I am not certain that 'VariableNamingRule' works as part of the options structure.
Try this instead:
test= readtimetable('test.csv', ,"VariableNamingRule","preserve");
EDIT — (25 Oct 2023 at 01:28)
It seems to work correctly here —
opts = detectImportOptions('test.csv',"VariableNamingRule","preserve");
test = readtimetable('test.csv', opts)
EDIT — (25 Oct 2023 at 11:45)
@Nina Sweeney — See if the same problem occurs with datastore. It also has a VariableNamingRule option. It is designed for large arrays, so it may work with your file.
.
2 件のコメント
Walter Roberson
2023 年 10 月 24 日
detectImportOptions does support VariableNamingRule . This is specifically documented in https://www.mathworks.com/help/matlab/ref/detectimportoptions.html#d126e365864
Star Strider
2023 年 10 月 25 日
I tried that recently and it threw an error, although I don’t remember the context. Using it as a name-value pair (copied and pasted, so spelling or typos were not an issue) in readtable worked.
Walter Roberson
2023 年 10 月 24 日
Works for me, provided that the number of header variables does not exceed the number of detected columns.
When I accidentally added extra numeric columns in the data, I did get trailing Var* variables being generated.
All of this requires that detectImportOptions was able to figure out which row had your variable names. If that goes wrong, then Sure, it might end up generating Var* variables.
filename = 'test.csv';
opts = detectImportOptions(filename,"VariableNamingRule","preserve");
%for this PARTICULAR test file, the datetime format is not recognized
opts = setvartype(opts,1,'datetime');
opts = setvaropts(opts,1,'InputFormat', 'MMM d uuuu HH:mm');
test = readtable('test.csv',opts)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Data Preprocessing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!