2015-04-12 27 views
0

我想在python中排序csv文件。在python中沒有發生csv排序

這裏是我的CSV文件

貓SampleData.csv

OrderDate,Region,Rep,Item,Units,Unit Cost,Total 
1/6/14,East,Jones,Pencil,95, 1.99 , 189.05 
1/23/14,Central,Kivell,Binder,50, 19.99 , 999.50 
2/9/14,"Central","Jardine","Pencil",36, 4.99 , 179.64 
2/26/14,Central,Gill,Pen,27, 19.99 , 539.73 
3/15/14,West,Sorvino,Pencil,56, 2.99 , 167.44 
4/1/14,East,Jones,Binder,60, 4.99 , 299.40 
4/18/14,Central,Andrews,Pencil,75, 1.99 , 149.25 
5/5/14,Central,Jardine,Pencil,90, 4.99 , 449.10 
5/22/14,West,Thompson,Pencil,32, 1.99 , 63.68 
6/8/14,East,Jones,Binder,60, 8.99 , 539.40 
12/4/15,Central,Jardine,Binder,94, 19.99 ," 1,879.06 " 
12/21/15,Central,Andrews,Binder,28, 4.99 , 139.72 

這裏是我的代碼

import csv 
import operator 

f = open('SampleData.csv') 

csv1 = csv.reader(f, delimiter=',') 

sort = sorted(csv1, key=operator.itemgetter(6)) 

for eachline2 in sort: 
     print eachline2 

f.close() 

這裏是我的結果:

['12/4/15', 'Central', 'Jardine', 'Binder', '94', ' 19.99 ', ' 1,879.06 '] 
['12/21/15', 'Central', 'Andrews', 'Binder', '28', ' 4.99 ', ' 139.72 '] 
['4/18/14', 'Central', 'Andrews', 'Pencil', '75', ' 1.99 ', ' 149.25 '] 
['3/15/14', 'West', 'Sorvino', 'Pencil', '56', ' 2.99 ', ' 167.44 '] 
['2/9/14', 'Central', 'Jardine', 'Pencil', '36', ' 4.99 ', ' 179.64 '] 
['1/6/14', 'East', 'Jones', 'Pencil', '95', ' 1.99 ', ' 189.05 '] 
['4/1/14', 'East', 'Jones', 'Binder', '60', ' 4.99 ', ' 299.40 '] 
['5/5/14', 'Central', 'Jardine', 'Pencil', '90', ' 4.99 ', ' 449.10 '] 
['6/8/14', 'East', 'Jones', 'Binder', '60', ' 8.99 ', ' 539.40 '] 
['2/26/14', 'Central', 'Gill', 'Pen', '27', ' 19.99 ', ' 539.73 '] 
['5/22/14', 'West', 'Thompson', 'Pencil', '32', ' 1.99 ', ' 63.68 '] 
['1/23/14', 'Central', 'Kivell', 'Binder', '50', ' 19.99 ', ' 999.50 '] 
['OrderDate', 'Region', 'Rep', 'Item', 'Units', 'Unit Cost', 'Total'] 

我不是肯定我做什麼錯了在這裏。

我這裏有兩個問題,你看

  1. 排序沒有發生。
  2. 我在最後一行得到標題。我想在第一行。

任何幫助極大的讚賞。

+0

數據排序非常好。看看'sorted(['Total','1,879.06','999.50'])''的輸出。如果你打算用csv文件做很多工作,你可以查看http://pandas.pydata.org/ – YXD

回答

2

實際上,排序是完全正確的,因爲您正在比較字符串(發生在逐個字符的基礎上),而不是數字。字符串'1,879.06'出現在'139.72'之前,因爲它按字典順序較小。

如果您想根據最後一列的數值對行進行排序,請將最後一列轉換爲浮點數或將您傳遞的函數更改爲key。請嘗試以下操作:

sort = sorted(csv1, key=lambda t: float(t[6])) 

但是,這將引發一個ValueError因爲列報頭不能被轉換爲數字。

要使標題出現在開頭,您可以嘗試將閱讀器對象csv1轉換爲列表,並且只對列表的一個片段進行排序,或更改key函數以確保不會啓動的字符串將數字轉換爲0,這應該將它們放在其他行之前(如果所有其他行的值都大於0)。

潛在的解決方案可能是這樣的:

import csv 
import operator 

def key_fn(row): 
    # Your strings contain both commas and dots, but commas can be removed 
    return float(row[6].replace(',', '')) 

f = open('SampleData.csv') 

csv1 = csv.reader(f, delimiter=',') 
header = next(csv1) # because csv reader supports the iterator protocol 
rows = sorted(csv1, key=key_fn) 

print header 

for row in rows: 
    print row 

f.close() 

對於數字可能更好地處理逗號,看this question

+0

非常感謝hgazibara,這對我有很大的幫助。 – user3330284