添加列和插入列

可以在表和DataFrame的末尾添加新的列,或者在指定位置插入新的列。

下面创建新的表T。

code.matlab
>> ID={'1';'2';'3';'4'};
>> Name={'张三';'李四';'杨二';'王五'};
>> Age=[18;19;17;21];
>> Height=[162;169;164;167];
>> Weight=[116;103;131;133];
>> T=table(Name,Age,Height,Weight, 'RowNames',ID);

使用点引用的方式在表后面添加“Married”列。

code.matlab
>> T.Married=[0;0;0;1]
T =
  4×5 table
           Name      Age    Height    Weight    Married
         ________    ___    ______    ______    _______
    1    {'张三'}    18      162       116         0
    2    {'李四'}    19      169       103         0
    3    {'杨二'}    17      164       131         0
    4    {'王五'}    21      167       133         1

可以在指定位置插入列。

下面使用addvars函数在表T中“Age”列的前面插入新列“Gender”。

code.matlab
>> Gender={'M';'M';'M';'M'};
>> T2=addvars(T,Gender,'Before','Age')
T2 =
  4×6 table
           Name      Gender    Age    Height    Weight    Married
         ________    ______    ___    ______    ______    _______
    1    {'张三'}    {'M'}     18      162       116         0
    2    {'李四'}    {'M'}     19      169       103         0
    3    {'杨二'}    {'M'}     17      164       131         0
    4    {'王五'}    {'M'}     21      167       133         1