我有一个CSV数据文件,其行可能有500多列,有些列少了很多.我需要转置它,以便每一行成为输出文件中的一列.问题是原始文件中的行可能并非都具有相同的列数,所以当我尝试数组的转置方法时,我得到:
`transpose':元素大小不同(12应该是5)(IndexError)
是否有替代的转置适用于不均匀的阵列长度?
我会插入空值来填充矩阵中的空洞,例如:
a = [[1, 2, 3], [3, 4]] # This would throw the error you're talking about # a.transpose # Largest row size = a.max { |r1, r2| r1.size <=> r2.size }.size # Enlarge matrix inserting nils as needed a.each { |r| r[size - 1] ||= nil } # So now a == [[1, 2, 3], [3, 4, nil]] aa = a.transpose # aa == [[1, 3], [2, 4], [3, nil]]