使用 FasterCSV 将不均匀的行转换为列

发布于 2024-07-08 15:44:30 字数 223 浏览 9 评论 0原文

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

“转置”:元素大小不同(12 应为 5)(IndexError)

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

I have a CSV data file with rows that may have lots of columns 500+ and some with a lot less. I need to transpose it so that each row becomes a column in the output file. The problem is that the rows in the original file may not all have the same number of columns so when I try the transpose method of array I get:

`transpose': element size differs (12 should be 5) (IndexError)

Is there an alternative to transpose that works with uneven array length?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山色无中 2024-07-15 15:44:30

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

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

I would insert nulls to fill the holes in your matrix, something such as:

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]]
救星 2024-07-15 15:44:30
# 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]]
# 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]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文