Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, how to read data column wise from a CSV file?

Tags:

I know how it is done row-wise

CSV.foreach(filename.csv) do |row|
  puts "#{row}"
end

But I am completely lost column wise?

like image 715
Pratik Bothra Avatar asked Jan 30 '13 06:01

Pratik Bothra


People also ask

Which function is used to read the data from the CSV file?

csv() Function. read. csv() function in R Language is used to read “comma separated value” files. It imports data in the form of a data frame.


1 Answers

test.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:

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.

like image 151
steenslag Avatar answered Oct 07 '22 17:10

steenslag