简体   繁体   English

排序csv python 2.7

[英]sorting csv python 2.7

I am trying to sort a csv file on column 3. python sorts the csv but for two rows. 我正在尝试对第3列的csv文件进行排序。python对csv进行了排序,但有两行。 Really confused 真的很困惑

here is the code i am using. 这是我正在使用的代码。

import csv
import operator
import numpy

sample = open('data.csv','rU')
csv1 = csv.reader(sample,delimiter=',')
sort=sorted(csv1,key=lambda x:x[3])
for eachline in sort:
    print eachline

and here is the o/p From the third row the O/P looks good. 这是o / p从第三行开始,O / P看起来不错。 Any ideas ? 有任何想法吗 ?

['6/23/02', 'Julian Jaynes', '618057072', '12.5']
['7/15/98', 'Timothy "The Parser" Campbell', '968411304', '18.99']
['10/4/04', 'Randel Helms', '879755725', '4.5']
['9/30/03', 'Scott Adams', '740721909', '4.95']
['10/4/04', 'Benjamin Radcliff', '804818088', '4.95']
['1/21/85', 'Douglas Adams', '345391802', '5.95']
['12/3/99', 'Richard Friedman', '60630353', '5.95']
['1/12/90', 'Douglas Hofstadter', '465026567', '9.95']
['9/19/01', 'Karen Armstrong', '345384563', '9.95']
['6/23/02', 'David Jones', '198504691', '9.95']
['REVIEW_DATE', 'AUTHOR', 'ISBN', 'DISCOUNTED_PRICE']

You are sorting strings, you need to use float(x[3]) 您正在对字符串进行排序,需要使用float(x[3])

sort=sorted(csv1,key=lambda x:float(x[3]))

If you want to sort by the third column it is x[2], casting to int : 如果要按第三列排序,则为x [2],强制转换为int

sort=sorted(csv1,key=lambda x:int(x[2]))

You will also need to skip the header to avoid a ValueError: 您还需要跳过标题以避免ValueError:

csv1 = csv.reader(sample,delimiter=',')
header = next(csv1)
sort=sorted(csv1,key=lambda x:int(x[2]))

Python will compare the strings character by character putting "2" after "12" unless you cast to int: 除非您强制转换为int,否则Python会逐个字符地比较字符串,将"2"放在"12"之后。

In [82]: "2" < "12"
Out[82]: False

In [83]: int("2") < int("12")
Out[83]: True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM