更新表并添加缺少的列- matlab

j9per5c4  于 7个月前  发布在  Matlab
关注(0)|答案(1)|浏览(73)
t1 = struct2table(struct('a',1, 'b',2, 'c',3));
t2 = struct2table(struct('a',NaN, 'c',4, 'd',5));

t1 =
    a    b    c
    _    _    _
    1    2    3

t2 =
     a     c    d
    ___    _    _
    NaN    4    5

我想在公共列上使用t2中的值更新t1,并将唯一的t2列添加到t1
我试过:

>> join(t1,t2, 'Keys',{'a','c'})
Error using tabular/join (line 172)
The key variables cannot contain any missing values.

>> outerjoin(t1,t2, 'Keys',{'a','c'}, 'Merge',1)

ans =

  2×4 table

     a      b     c     d 
    ___    ___    _    ___

      1      2    3    NaN
    NaN    NaN    4      5

所需输出:

a      b     c     d 
    ___    ___    _    ___

    NaN      2    4     5
yqkkidmi

yqkkidmi1#

你的定义是
在公共列上使用t2中的值更新t1,并将唯一的t2列添加到t1
这听起来相当于
使用t2中的所有列,以及t1中不存在于t2中的列
这更容易解析成代码,因为您可以

t1 = struct2table(struct('a',1, 'b',2, 'c',3));
t2 = struct2table(struct('a',NaN, 'c',4, 'd',5));

t1Vars = t1.Properties.VariableNames;
t2Vars = t2.Properties.VariableNames;
t3 = [t1( :, ~ismember(t1Vars, t2Vars)), t2];

这给

t3 =
  1×4 table
    b     a     c    d
    _    ___    _    _

    2    NaN    4    5

列顺序与您的“期望输出”不完全匹配,这看起来像是您希望首先对t1中的变量进行优先级排序,您可以使用

t3 = t3( :, [t1Vars, setdiff(t2Vars,t1Vars,'stable')] );

它给出了所需的输出

t3 =
  1×4 table
     a     b    c    d
    ___    _    _    _

    NaN    2    4    5

相关问题