Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: categorising a list by orders of magnitude

Tags:

python

I have a nested list with values:

list = [
...
['Country1', 142.8576737907048, 207.69725105029553, 21.613192419863577, 15.129178465784218],
['Country2', 109.33326343550823, 155.6847323746669, 15.450489646386226, 14.131554442715336],
['Country3', 99.23033109735835, 115.37122637190915, 5.380298424850267, 5.422030104456135],
...]

I want to count values in the second index / column by order of magnitude, starting at the lowest order of magnitude and ending at the largest...e.g.

99.23033109735835 = 10 <= x < 100
142.8576737907048 = 100 <= x < 1000
             9432 = 1000 <= x < 10000

The aim is to output a simple char (#) count for how many index values fall in each category, e.g.

  10 <= x < 100: ###
100 <= x < 1000: #########

I've started by grabbing the max() and min() values for the index in order to automatically calculate the largest and smalles magnitude categories, but I'm not sure how to associate each value in the column to an order of magnitude...if someone could point me in the right direction or give me some ideas I would be most grateful.

like image 996
Rookierookie Avatar asked May 30 '13 14:05

Rookierookie


1 Answers

Extending Useless' answer to all real numbers, you can use:

import math

def magnitude (value):
    if (value == 0): return 0
    return int(math.floor(math.log10(abs(value))))

Test cases:

In [123]: magnitude(0)
Out[123]: 0

In [124]: magnitude(0.1)
Out[124]: -1

In [125]: magnitude(0.02)
Out[125]: -2

In [126]: magnitude(150)
Out[126]: 2

In [127]: magnitude(-5280)
Out[127]: 3
like image 71
awwsmm Avatar answered Nov 16 '22 00:11

awwsmm