Search code examples
pythonpandasnetworkxstellargraph

Letter number combo to float in python


def computefeatures(node_id):
    return [ord(node_id), len(node_id)]

I am computing features for my node ids which are a combo of a letter and a number. ord will not work, is there another work around for this.

my list is:

ln0
Out[88]: 
0     C1
1     C2
2     C3
3     C4
4     C5
5     C6
6     G1
7     I1
8     O1
9     P1
10    P2
11    P3
12    R1
13    R2
14    R3
15    R4
16    R5
17    R6
dtype: object

Solution

  • If your node consist of a single letter followed by an integer, and all you want to do is map them to floats, this can be done in various ways.

    One way is to convert your node_id into a hex string of the sort that is returned by the float method hex (for example, (3.14).hex() = '0x1.91eb851eb851fp+1'). Take the ord of the letter, convert it to a hexstring, and use it as the decimal part of the mantissa. Take the integer part and use it as the exponent. Once you create the string, map it to a float using the class method float.fromhex:

    def compute_feature(node_id):
        n = ord(node_id[0])
        i = node_id[1:]
        hex_string = '0x1.' + hex(n)[2:] + 'p+' + i
        return float.fromhex(hex_string)
    

    For example,

    >>> compute_feature('C1')
    2.5234375
    

    This approach has the nice feature that you can use the float method hex and a small amount of parsing to recover the node id from the float.