How to add a new column in a table and then write on a file only some columns?
조회 수: 11 (최근 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!