How to add a new column in a table and then write on a file only some columns?
13 次查看(过去 30 天)
显示 更早的评论
Hi guys,
I've a simple code that reads data from a .csv file (atteched below). I have 56 rows, the first one is the header row and the the others contain data.
I want to create a new column contaning integer numbers that count the number of rows (so a column that contains: 1,2,3,4,..,55) and I want to call this column "index", then I want to put this one as first column of my table and I want to write it on a new .csv file by excluding the row called "name". Can you help me?
Here my code:
clear all; close all; clc;
% Definition of path names and file names
file_data_ast = 'NEOs_asteroids.csv';
% Setting of data import options
opt = detectImportOptions(file_data_ast);
opt = setvaropts(opt,'Type','string');
% Import table of text data
Tab_ast_str = readtable(file_data_ast, opt);
disp(['Asteroids (NEOs) no. : ',num2str(height(Tab_ast_str))]);
Here what I want to obtain:
0 个评论
采纳的回答
Turlough Hughes
2022-2-8
编辑:Turlough Hughes
2022-2-8
T = readtable('https://uk.mathworks.com/matlabcentral/answers/uploaded_files/887485/NEOs_asteroids.csv');
T = removevars(T,'name');
T = addvars(T,(1:height(T)).','Before','pdes','NewVariableNames','index');
head(T)
To save it you can use:
writetable(T,'myNewTable.csv')
更多回答(1 个)
Enrico Gambini
2022-2-8
编辑:Enrico Gambini
2022-2-8
Hello Giuseppe.
To create your column of indexes you can do the following:
idx=[1:height(Tab_ast_str)];
then
Tab_ast_str.indexes=idx; %add the new column called "indexes" at the end of the table
Tab_ast_str=movevars(Tab_ast_str,'indexes','Before','pdes');%move your column at first position
Tab_ast_str=removevars(Tab_ast_str,'name'); %remove the column called "name"
writetable(Tab_ast_str,'new_table.csv'); %export the new table
Hope it helps!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!