gpt4 book ai didi

ruby - 纯 ruby : filtered csv dates by #select but now want to obtain another column based on those date ranges

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:47 24 4
gpt4 key购买 nike

所以基本上我试图通过 Ruby 在一个巨大的 csv 文件中查找一些信息(注意我不想要 excel 解决方案),我已经将 unix 时间戳转换为适当的时间对象并对它们进行排序并通过 #select 过滤它们。我正在尝试查找有关给定此特定时间范围内的 purchase_amt 的信息(我用 start_date、end_date 表示)。

目前我只有一个通过巨大的 csv 过滤的时间数组,但是我如何使用我的代码来获取 csv 中给出的 purchase_amt?

Unix_time    purchase_amt
1352948920 12.40

require 'csv'
require 'date'

start_date = DateTime.rfc3339('2014-06-22T00:00:00Z').to_time.to_i
end_date = DateTime.rfc3339('2014-07-22T00:00:00Z').to_time.to_i

csv = CSV.parse('sample_data.csv', headers: true, encoding: 'ISO-8859-1')

csv.each do |row|
if (row['created_at'] >= start_date && row['created_at'] <= end_date)
final_arry<< row
end
end

puts csv

最佳答案

如果你有一个巨大的 CSV,你应该使用 CSV.foreach .它逐行解析而不将整个文件加载到内存中。

Range#cover?也有帮助:

Returns true if obj is between the begin and end of the range.

如果可以,您还应该在 block 内进行所有计算,而不返回也可能变得巨大的新数组。看起来你确实想要一个巨大的数组,所以这里是:

require 'csv'

amounts = []

start_date = Time.new(2012, 1, 22)
end_date = Time.new(2014, 7, 22)

search_range = (start_date.to_i..end_date.to_i)

CSV.foreach('data.csv', headers: true, col_sep: "\s", skip_blanks: true) do |row|
next unless search_range.cover?(row['Unix_time'].to_i)
amounts << row['purchase_amt'].to_f
end

p amounts

关于ruby - 纯 ruby : filtered csv dates by #select but now want to obtain another column based on those date ranges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41931547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com