使用Ruby CSV提取一列 [英] Using Ruby CSV to extract one column
问题描述
我一直在尝试从csv文件中获取单列.
I've been trying to work with getting a single column out of a csv file.
我已经阅读了文档, http://www.ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html 但仍然不太了解如何使用它.
I've gone through the documentation, http://www.ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html but still don't really understand how to use it.
如果使用CSV.table
,与CSV.read
相比,响应速度非常慢.我承认我要加载的数据集非常大,这正是我只想从中获取单个列的原因.
If I use CSV.table
, the response is incredibly slow compared to CSV.read
. I admit the dataset I'm loading is quite large, which is exactly the reason I only want to get a single column from it.
我的请求目前看起来像这样
My request is simply currently looks like this
@dataTable = CSV.table('path_to_csv.csv')
当我调试时,我得到一个响应
and when I debug I get a response of
#<CSV::Table mode:col_or_row row_count:2104 >
The documentation says I should be able to use by_col(), but when I try to output
<%= debug @dataTable.by_col('col_name or index') %>
它给我未定义的方法'col'错误"
It gives me "undefined method 'col' error"
有人可以向我解释如何使用CSV吗?以及是否有一种方法可以使用读取"而不是表"更快地获取列?
Can somebody explain to me how I'm supposed to use CSV? and if there is a way to get columns faster using 'read' instead of 'table'?
我使用的是Ruby 1.92,它表示它使用的是fastCSV,因此不需要使用FasterCSV gem.
I'm using Ruby 1.92, which says that it is using fasterCSV, so I don't need to use the FasterCSV gem.
推荐答案
要从csv中抽出一列,我可能会执行以下操作:
To pluck a column out of a csv I'd probably do something like the following:
col_data = []
CSV.foreach(FILENAME) {|row| col_data << row[COL_INDEX]}
这应该比CSV上的任何操作都要快.
That should be substantially faster than any operations on CSV.Table
这篇关于使用Ruby CSV提取一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!