此问题不仅适用于 MATLAB 用户 - 如果您知道PSEUDOCODE中问题的答案,请随时留下您的答案!
我有两个表 Ta 和 Tb 有不同的行数和不同的列数。内容都是单元格文本,但将来可能还会包含单元格编号。
我想根据以下规则将这些表的内容合并在一起:
- 取
Ta(i,j)
if的Tb(i*,j*)
值为空,反之亦然。 - 如果两者都可用,则取 的值
Ta(i,j)
(并且可选地,检查它们是否相同)。
然而,棘手的部分是我们没有唯一的行键,我们只有唯一的列键。i*
请注意,我在和之间进行了区分i
。原因是 Ta 中的行可以位于与 Tb 不同的索引处,对于列j*
和 也是如此j
。影响是:
- 我们首先需要确定 Ta 的哪一行对应于 Tb 的行,反之亦然。我们可以通过尝试交叉匹配表共有的任何列来做到这一点。但是,我们可能找不到匹配项(在这种情况下,我们不会将一行与另一行合并)。
问题
我们如何才能以最有效的方式将这两个表的内容合并在一起?
这里有一些资源可以更详细地解释这个问题:
1. Matlab 示例:
Ta = cell2table({...
'a1', 'b1', 'c1'; ...
'a2', 'b2', 'c2'}, ...
'VariableNames', {'A','B', 'C'})
Tb = cell2table({...
'b2*', 'c2', 'd2'; ...
'b3', 'c3', 'd3'; ...
'b4', 'c4', 'd4'}, ...
'VariableNames', {'B','C', 'D'})
结果表 Tc 应该是这样的:
Tc = cell2table({...
'a1' 'b1' 'c1' ''; ...
'a2' 'b2' 'c2' 'd2'; ...
'' 'b3' 'c3' 'd3'; ...
'' 'b4' 'c4' 'd4'}, ...
'VariableNames', {'A', 'B','C', 'D'})
2. 可能的第一步
我尝试了以下方法:
Tc = outerjoin(Ta, Tb, 'MergeKeys', true)
哪个工作顺利,但问题是它缺少看起来相似的行的堆叠。例如上面的命令产生:
A B C D
____ _____ ____ ____
'' 'b2*' 'c2' 'd2'
'' 'b3' 'c3' 'd3'
'' 'b4' 'c4' 'd4'
'a1' 'b1' 'c1' ''
'a2' 'b2' 'c2' ''
这里的行
'' 'b2*' 'c2' 'd2'
'a2' 'b2' 'c2' ''
应该合并为一个:
'a2' 'b2' 'c2' 'd2'
所以我们需要多一步将这两个堆叠在一起?
3. 障碍示例
如果我们有类似的东西:
Ta =
A B C
____ _____ ____
'a1' 'b1' 'c1'
'a2' 'b2' 'c2'
Tb =
A B C
____ _____ ____
'a1' 'b2' 'c3'
那么问题就出现了 b 中的行是否应该与 a 的第 1 行或第 2 行合并,还是应该将所有行合并或只是作为单独的行?关于如何处理这些类型的情况的想法也很好。