How to add a new column in a table and then write on a file only some columns?
18 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Turlough Hughes
le 8 Fév 2022
Modifié(e) : Turlough Hughes
le 8 Fév 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')
Plus de réponses (1)
Enrico Gambini
le 8 Fév 2022
Modifié(e) : Enrico Gambini
le 8 Fév 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!
Voir également
Catégories
En savoir plus sur Tables dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!