在 Ruby 中,如何从 CSV 文件中明智地读取数据列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14598302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Ruby, how to read data column wise from a CSV file?
提问by Pratik Bothra
I know how it is done row-wise
我知道它是如何按行完成的
CSV.foreach(filename.csv) do |row|
puts "#{row}"
end
But I am completely lost column wise?
但我完全迷失了专栏?
采纳答案by Pratik Bothra
This is the solution guys:
这是解决方案伙计们:
CSV.foreach(filename).map { |row| row[0] }
Sorry for posting it in the correct format so late.
很抱歉这么晚才以正确的格式发布它。
回答by steenslag
test.csv:
测试.csv:
name,surname,no1,no2,no3,date
Raja,Palit,77489,24,84,12/12/2011
Mathew,bargur,77559,25,88,01/12/2011
harin,Roy,77787,24,80,12/12/2012
Soumi,paul,77251,24,88,11/11/2012
Acces by cols:
通过 cols 访问:
require 'csv'
csv = CSV.read('test.csv', :headers=>true)
p csv['name'] #=>["Raja", "Mathew", "harin", "Soumi"]
#or even:
t = CSV.table('test.csv')
p t[:no1] #=> [77489, 77559, 77787, 77251]
Note that in the last case the cols are accessed by their symbolized name and that strings are converted to numbers when possible.
请注意,在最后一种情况下,cols 是通过它们的符号名称访问的,并且在可能的情况下将字符串转换为数字。
回答by Sachin R
Transposeyour CSV file. By doing this your rows covert to column and viceversa. Below a simple example of transpose.
转置您的 CSV 文件。通过这样做,您的行将转换为列,反之亦然。下面是一个简单的转置示例。
irb(main):001:0> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]].transpose
=> [["1", "4", "7"], ["2", "5", "8"], ["3", "6", "9"]]
回答by boulder_ruby
Bored so decided to cook up an alternate solution here. Only works (here) if the first row has the max number of columns
无聊所以决定在这里准备一个替代解决方案。仅在第一行具有最大列数时才有效(此处)
columns = {}
rows.first.each_with_index do |col, i|
columns[i] = []
end
rows.each do |row|
row.each_with_index do |cell, i|
columns[i] = columns[i] + [cell]
end
end
Now you should be able to access each column by its index
现在您应该能够通过索引访问每一列

