【问题标题】:Converting uneven rows to columns with FasterCSV使用 FasterCSV 将不均匀的行转换为列
【发布时间】:2010-09-20 00:43:52
【问题描述】:

我有一个 CSV 数据文件,其中的行可能有很多 500+ 列,而有些列则少得多。我需要转置它,以便每一行成为输出文件中的一列。问题是原始文件中的行可能并不都有相同的列数,所以当我尝试数组的转置方法时,我得到:

`transpose':元素大小不同(12 应该是 5)(IndexError)

是否有替代转置的方法来处理不均匀的数组长度?

【问题讨论】:

  • 伙计,Ruby 已将转置内置到数组中,这真是太好了。我通常会用其他语言编写脚本。

标签: arrays ruby transpose fastercsv


【解决方案1】:

我会插入空值来填充矩阵中的空洞,例如:

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]]

【讨论】:

    【解决方案2】:
    # 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]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-04
      • 2019-12-20
      • 2020-09-07
      • 2017-01-07
      • 2020-01-04
      • 2011-03-25
      • 2018-04-23
      • 2021-02-21
      相关资源
      最近更新 更多