In Ruby, How to Read Data Column Wise from a CSV File

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

This is the solution guys:

CSV.foreach(filename).map { |row| row[0] }

Sorry for posting it in the correct format so late.

Rails write a csv file column wise

You could use Array#transpose, which will flip your rows to columns. A simple example:

> a = [['name', 'charles', 'dave'],['age', 24, 36],['height', 165, 193]]
=> [["name", "charles", "dave"], ["age", 24, 36], ["height", 165, 193]]
> a.transpose
=> [["name", "age", "height"], ["charles", 24, 165], ["dave", 36, 193]]

Thus, assuming dataset_columns is an array:

require 'csv'    

dataset_columns = Datacolumn.all(:conditions => ["dataset_id = ?", 6], :order => "columnnr ASC").uniq

csv_file = CSV.generate do |csv|
csv << dataset_columns.transpose
end

How to check for a column data and extract data on the same row? CSV on Ruby

You can access to Security and Level, and any other value you define in your header as object['header'].

In this case the object is each row for the iteration, and the values are Severity and Level, so:

require 'csv'

file = '/path_to_data/data.csv'
CSV.foreach(file, headers: true, col_sep: ';') do |row|
p [row['Severity'], row['Level']]
end

# ["Least", "1"]
# ["Average", "2"]
# ["Normal", "3"]
# ["High", "4"]
# ["Severe", "5"]

Reading a specific column of data from a text file in Ruby

You can still use CSV; just set the column separator to the space character:

require 'csv'

CSV.open('data', :col_sep=>" ").each do |row|
puts row[2].to_f
end

You don't need CSV, however, and if the whitespace separating fields is inconsistent, this is easiest:

File.readlines('data').each do |line|
puts line.split[2].to_f
end

I'd recommend breaking the task down mentally to:

  1. How can I read the lines of a file?
  2. How can I split a string around whitespace?

Those are two problems that are easy to learn how to handle.

How to find a specific row in csv

Use .find

csv = CSV.read('sampler.csv', headers: true)

puts csv.find {|row| row['NAME'] == 'Tom'} #=> returns first `row` that satisfies the block.

Finding maximum CSV field sizes for large file using Ruby

You're using CSV.foreach wrong, it takes a string for a filename:

field_lengths = {}

CSV.foreach(data_file, :headers => true, :header_converters => :symbol) do |csv_row|
csv_row.each do |k, v|
field_lengths[k] = [field_lengths[k] || 0, v.length].max
end
end

pp field_lengths

Adding columns to CSV with Ruby

CSV writer expects a flattened array, not the tuple string => array:

- csv << row
+ csv << row.flatten

Hope it helps.



Related Topics



Leave a reply



Submit