0

I want to sort my CSV file with the first column. The first column has strings in it but the values are numbers. So I want to sort it as an integer. I know I can sort using the following -

sortedList = sorted(mycsv, key=lambda t: float(t[0]))

But this gives the following error -

ValueError: invalid literal for float(): 14,481.72

I read a couple of SO questions like this and found out that the solution to get rid of that error is by doing this -

float(value.replace(',',''))

However I do not know how to do this while sorting using lambda function. I somehow cannot put this logic into the first line of code.

Community
  • 1
  • 1
newbie
  • 325
  • 2
  • 4
  • 19

1 Answers1

0

Just replace in the lambda, you want to sort by t[0] the first element so you need to convert that element to a float in your lambda:

float(t[0].replace(",",""))

sorted(mycsv, key=lambda t: float(t[0].replace(",","")))

In [12]: l = ["5,543.23","14,481.72","10,1000.34","8,581.72"]

In [13]:  sorted(l, key=lambda t: float(t.replace(",","")))
Out[13]: ['5,543.23', '8,581.72', '14,481.72', '10,1000.34']
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321