0

I am attempting to sort my csv file by a specific column. That is easy enough with this below code:

with open("outfile.csv","rb") as infile,open("outfile.csv","wb") as outfile:
    reader= csv.reader(infile,delimiter=',')
    writer= csv.writer(outfile)
    sort= sorted(reader,key=operator.itemgetter(7), reverse= True)
    for eachline in sort:
        writer.writerow(eachline)

In my example however, it will sort but will sort in an odd way. For example, it would return the file to me descending in this order: 3.8,3.7,3.1,21.7,21.6,2.8.

Since this is causing me an issue, I would like to fix this; if it can't, instead I'd like to sort by largest length if that is possible.

This sounds confusing but this is the issue I am having. Any help would be great.

Thank you.

2
  • Looks like alphabetical order, you may need to consider how you cast it to float for the sorting, assuming you want numerical order, e.g. key=lambda x: float(x[7]) Commented Apr 9, 2015 at 2:45
  • My issue now is that I have the header first, thus making it a string at runtime when I need it to be a float. Commented Apr 9, 2015 at 3:01

1 Answer 1

2

Try sorting float values instead of str values:

sort= sorted(reader,key=lambda x:float(x[7]), reverse= True)
Sign up to request clarification or add additional context in comments.

2 Comments

My issue now is that I have the header first, thus making it a string at runtime when I need it to be a float
If you have a header in your input, try reading it singly, storing it in some variable, then sorting the remaining lines. When you write the result, write the header first and then write the sorted result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.