필터 지우기
필터 지우기

How to add a new column in a table and then write on a file only some columns?

조회 수: 23 (최근 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))]);
Asteroids (NEOs) no. : 28071
Here what I want to obtain:

채택된 답변

Turlough Hughes
Turlough Hughes 2022년 2월 8일
편집: Turlough Hughes 2022년 2월 8일
I like to use addvars and removevars for this:
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)
ans = 8×11 table
index pdes epoch a e i om w ma q ad _____ ____ __________ ______ _______ ______ ______ ______ _______ _______ ______ 1 433 2.4596e+06 1.4583 0.22273 10.828 304.3 178.9 246.9 1.1335 1.7831 2 719 2.4596e+06 2.6375 0.54696 11.575 183.86 156.23 278.2 1.1949 4.0801 3 887 2.4596e+06 2.4732 0.57049 9.3941 110.43 350.49 86.607 1.0623 3.8841 4 1036 2.4596e+06 2.6658 0.53312 26.678 215.52 132.43 140.65 1.2446 4.0871 5 1221 2.4596e+06 1.9187 0.43584 11.883 171.32 26.644 261.04 1.0825 2.755 6 1566 2.4596e+06 1.0781 0.82694 22.804 87.962 31.438 0.33029 0.18657 1.9696 7 1580 2.4596e+06 2.1973 0.48716 52.079 62.292 159.51 16.629 1.1269 3.2677 8 1620 2.4596e+06 1.2457 0.33536 13.338 337.18 276.95 300.49 0.82793 1.6634
To save it you can use:
writetable(T,'myNewTable.csv')

추가 답변 (1개)

Enrico Gambini
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 CenterFile Exchange에서 Tables에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by