3

I want to load a CSV-file with two columns (each with a name and a row of numbers) and save only the numbers of the two columns in two different arrays. Then I want to make some calculations with the data in those two columns, using two arrays to save the numbers of each column.

This is what I still have:

require 'csv'
filename = 'file.csv'
csv_data = CSV.read(filename, :col_sep => ";")
csv_data.shift
csv_data.each_with_index { |column, index_c|
  average = 0
  column.each_with_index{ |element, index_e|
    csv_data[index_c][index_e] = element.to_i
  }
}
csv_data = csv_data.transpose

How can I split the columns of csv_data in two arrays ?

2
  • Can you include an example of what the CSV file looks like and what output you're looking for? Commented Apr 6, 2012 at 20:27
  • the csv looks like: data1 data2 1 5 2 6 3 7 4 8 i need each column in one single array. here arr1, including (1,2,3,4), and arr2 including (5,6,7,8). Commented Apr 6, 2012 at 20:33

1 Answer 1

3

This should do the trick for you creating your two column arrays without wasting storage reading the whole file redundantly into csv_data.

require 'csv'
filename = 'file.csv'
arr1 = []
arr2 = []
CSV.foreach(filename, :col_sep => ";", :return_headers => false) do |row|
  arr1 << row[0].to_i
  arr2 << row[1].to_i
end
Sign up to request clarification or add additional context in comments.

2 Comments

now I have the problem, that I want to calculate the yield by arr1.each_cons(2) { |c| arr3.push(Math.log(c[1]/c[0]))}. there is the error: divided by 0, but why? where is the mistake?
I would presume because one of the values is arr1 is 0 and c[1]/c[0] raises ZeroDivisionError. arr1.each_with_index{|v,i| puts "found zero at index #{i}" if v == 0 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.