How to add a new column in a table and then write on a file only some columns?
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Giuseppe
am 8 Feb. 2022
Kommentiert: Giuseppe
am 8 Feb. 2022
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/887490/image.png)
0 Kommentare
Akzeptierte Antwort
Turlough Hughes
am 8 Feb. 2022
Bearbeitet: Turlough Hughes
am 8 Feb. 2022
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')
Weitere Antworten (1)
Enrico Gambini
am 8 Feb. 2022
Bearbeitet: Enrico Gambini
am 8 Feb. 2022
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!
Siehe auch
Kategorien
Mehr zu Text Files finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!