Python Forum
How do you sort a table by one column?? (of floats)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do you sort a table by one column?? (of floats)
#1
Been struggling all day to figure this out, every guide online only shows how to use the sorted() function to change a table by a column alphabetically, there is no help anywhere if you are trying to sort by floats. Wall

#!/usr/bin/python

import sys
import urllib2
import json
import operator
from tabulate import tabulate

def sort_table(table, col):
	return sorted(table, key=operator.itemgetter(col))

total_num_coins = 500
num_displayed_coins = 50
url = "https://api.coinmarketcap.com/v1/ticker/?convert=AUD&limit=" + str(total_num_coins)

chartheaders = ["Position","Name","Market Cap","USD","Volume 24h","Change 24h", "Change 7d"]

data = urllib2.urlopen(url).read()
data = json.loads(data)

xcount = 0
table = []

percentage_winner_table = []
percentage_winner_table_length = 10

for d in data[0:num_displayed_coins]:
	if xcount < num_displayed_coins:
		table.append([d['rank'],d['name'],d['market_cap_usd'],d['price_usd'],d['24h_volume_usd'],d['percent_change_24h'],d['percent_change_7d']])
	xcount = xcount + 1

print '\n~=Todays Top ' + str(percentage_winner_table_length) + ' Winners!=~'
for row in sort_table(table, 5):
	percentage_winner_table.append(row)

print tabulate(percentage_winner_table,chartheaders,numalign="left",stralign="left",floatfmt=".2f")
This outputs:

~=Todays Top 10 Winners!=~
Position    Name              Market Cap       USD       Volume 24h      Change 24h    Change 7d
----------  ----------------  ---------------  --------  --------------  ------------  -----------
33          Ardor             1540577101.00    1.54      4107470.00      -0.06         -19.96
2           Ethereum          127911164630.00  1319.99   9519530000.00   -0.51         38.31
44          Veritaseum        959632708.00     471.18    841014.00       -0.59         25.41
12          NEO               7919470000.00    121.84    325600000.00    -0.97         21.75
6           NEM               13521689998.00   1.50      99261000.00     -1.04         -19.47
19          Ethereum Classic  3677233548.00    37.13     823540000.00    -1.11         10.40
14          Monero            6340876774.00    406.78    255541000.00    -1.20         -1.21
42          DigiByte          1058699135.00    0.11      76977900.00     -1.56         39.76
20          Lisk              3377092764.00    28.90     96994400.00     -1.82         36.17
38          Steem             1261803080.00    5.12      14579900.00     -10.90        -33.96
49          Hshare            828758533.00     19.51     194733000.00    -15.01        -20.89
35          Dogecoin          1443036775.00    0.01      88577800.00     -2.01         38.57
9           Stellar           10006314001.00   0.56      234255000.00    -2.32         -37.13
5           Cardano           19973411403.00   0.77      224343000.00    -2.38         -35.32
As you can see it's listing them by column 5 alphabetically instead of numerically. (grrrr!)

How can i get the sorted() function to sort this table numerically?

Something simple i tried that failed:

    return sorted(table, key=float(operator.itemgetter(col)))
TypeError: float() argument must be a string or a number
Reply
#2
return sorted(table, key=lambda k: float(k[col]))
99 percent of computer problems exists between chair and keyboard.
Reply
#3
Thanks for the awesome tip, this code works for listing the lowest value first.

How might i list the highest value first? I tried adding 'return=True' like so:

return sorted(table, key=lambda k: float(k[col]), reverse=True)
But it fails like so:

  File "coin-analysis.py", line 42, in <lambda>
    return sorted(table, key=lambda k: float(k[col]), reverse=True)
TypeError: float() argument must be a string or a number
Reply
#4
for row in reversed(sort_table(table, 5)):
Adding the reversed() function like so gets the reverse sort i need. :)

Thanks everyone!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  When is it safe to compare (==) two floats? Radical 4 739 Nov-12-2023, 11:53 AM
Last Post: PyDan
  Find a string from a column of one table in another table visedwings049 8 1,181 Sep-07-2023, 03:22 PM
Last Post: deanhystad
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,328 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  How to perform DESC table sort on dates stored as TEXT type. hammer 7 2,235 Mar-15-2022, 01:10 PM
Last Post: hammer
  floats 2 decimals rwahdan 3 1,639 Dec-19-2021, 10:30 PM
Last Post: snippsat
  pandas pivot table: How to find count for each group in Index and Column JaneTan 0 3,323 Oct-23-2021, 04:35 AM
Last Post: JaneTan
  Sort List of Lists by Column Nju 1 11,583 Apr-13-2021, 11:59 PM
Last Post: bowlofred
  Data extraction from a table based on column and row names tgottsc1 1 2,417 Jan-09-2021, 10:04 PM
Last Post: buran
  rounding and floats Than999 2 3,126 Oct-26-2020, 09:36 PM
Last Post: deanhystad
  int, floats, eval menator01 2 2,449 Jun-26-2020, 09:03 PM
Last Post: menator01

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020