500 以上の列が多数ある行と、それよりも少ない行を含む CSV データ ファイルがあります。各行が出力ファイルの列になるように転置する必要があります。問題は、元のファイルの行がすべて同じ数の列を持っているとは限らないため、配列の転置方法を試すと次のようになることです。
`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]]
# Intitial CSV table data
csv_data = [ [1,2,3,4,5], [10,20,30,40], [100,200] ]
# Finding max length of rows
row_length = csv_data.map(&:length).max
# Inserting nil to the end of each row
csv_data.map do |row|
(row_length - row.length).times { row.insert(-1, nil) }
end
# Let's check
csv_data
# => [[1, 2, 3, 4, 5], [10, 20, 30, 40, nil], [100, 200, nil, nil, nil]]
# Transposing...
transposed_csv_data = csv_data.transpose
# Hooray!
# => [[1, 10, 100], [2, 20, 200], [3, 30, nil], [4, 40, nil], [5, nil, nil]]