我如何通过ID然后按PRICE对.csv文件进行唯一排序,然后,如果可能,由DATE进行排序。这是一个示例文件:
"Date","other","Id","other","Price"
"01/01/2016","3","6452312546-232","a","4.5"
"01/03/2016","1","4375623416-345","b","56.25"
"01/03/2016","6","4375623416-345","c","0"
"01/03/2016","5","4375623416-345","d","0"
"02/01/2016","4","6452312546-232","e","34.21"
我希望输出首先按ID排序,以便所有内容先按ID分组,然后将它们分组后,按PRICE对各个组进行排序,然后按最近的日期对现在的PRICE排序组进行排序群组。所以我把它作为输出:
"Date","other","Id","other","Price"
"02/01/2016","4","6452312546-232","e","34.21"
"01/01/2016","3","6452312546-232","a","4.5"
"01/03/2016","1","4375623416-345","b","56.25"
"01/03/2016","6","4375623416-345","c","0"
"01/03/2016","5","4375623416-345","d","0"
这是清楚的吗?如果不是,请告诉我。
答案 0 :(得分:1)
假设此CSV文件足够小以便可以安全地加载到内存中,您可以将文件读入哈希并从那里对其进行排序。
require 'csv'
table = CSV.read('file.csv', headers: true).map { |row| Hash[row] }
table.sort_by { |k, _| [k["id"], k["price"].to_f, Date.parse(k["date"])] }
虽然,如果您最初按ID进行排序,那么您将失去价格和日期字段的任何粒度。