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

前端 未结 5 1624
忘了有多久
忘了有多久 2020-12-30 01:15

I know how it is done row-wise

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

But I am completely lost column wise?

相关标签:
5条回答
  • 2020-12-30 01:48

    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.

    0 讨论(0)
  • 2020-12-30 01:54

    This is the solution guys:

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

    Sorry for posting it in the correct format so late.

    0 讨论(0)
  • 2020-12-30 01:54

    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

    0 讨论(0)
  • 2020-12-30 01:59

    The method 'by_col' provides you output based on your column selection.

    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
    

    Code:

    CSV.parse(File.open('test_csv'), headers: true).by_col['surname']
    

    Output:

    ['Palit','bargur','Roy','paul']
    
    0 讨论(0)
  • 2020-12-30 02:01

    Transpose your CSV file. By doing this your rows covert to column and viceversa. Below a simple example of transpose.

       irb(main):001:0> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]].transpose
        => [["1", "4", "7"], ["2", "5", "8"], ["3", "6", "9"]]
    
    0 讨论(0)
提交回复
热议问题