2016-09-29 85 views
0

如何通過ID,然後按照PRICE,然後在可能的情況下按DATE對.csv文件進行唯一排序。下面是一個例子文件:如何排序您從.csv文件中排序的內容

"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排序的組。所以我會得到這個作爲輸出:

"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

我試過[this](http://stackoverflow.com/questions/28942306/sort-row-of-a-csv-file-by-first-value),但是我得到一個錯誤:'block(2水平)在移位':第2行中的非法引用'這就是這一行:'my_csv = CSV.read'file.csv'' – Forwarding

+0

你的日期是「日/月/年」嗎? –

+0

@CarySwoveland,我運行ruby 2.0.0,是的,他們是dd/mm/yyyy。 – Forwarding

回答

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進行排序,您將失去價格和日期字段的更細粒度。

+0

這就是我的想法!但我不知道哈希可以做到這一點。 – Forwarding

+0

我使用'to_h'出現錯誤,爲什麼? – Forwarding

+0

運行'to_h'時看到什麼錯誤? – dlachasse