더 FasterCSV를 사용하여 고르지 않은 행을 열로 변환합니다
문제
열이 500 이상이고 일부는 훨씬 적은 행이있는 CSV 데이터 파일이 있습니다. 각 행이 출력 파일의 열이되도록 전환해야합니다. 문제는 원본 파일의 행에 모두 동일한 수의 열을 가질 수 없으므로 전환 배열 메소드를 시도 할 때 다음을 얻을 수 있다는 것입니다.
`jastose ': 요소 크기가 다릅니다 (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]]
제휴하지 않습니다 StackOverflow