DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Transpose CSV Dataset Using FasterCSV

08.06.2008
| 5657 views |
  • submit to reddit
        Takes a dataset such as:
 $10,000 	 $15,000 	 $20,000 
 $30,000 	 $35,000 	 $40,000 
1	1	2
1	1	2
1	1	2
2	2	2

and converts it to
1000000,3000000,1,1,1,2
1500000,3500000,1,1,1,2
2000000,4000000,2,2,2,2

  def transpose_csv_fixture_file!(path)
    converter = proc{ |v| v =~ /\$/ ? v.gsub(/[$,]/, "").to_i * 100 : v.to_f }
    data = FasterCSV.read(path, :col_sep => "\t", :converters => converter ).transpose
    FasterCSV.open(path, "w") { |csv| data.each{ |line| csv << line } }
  end