pythonarraysstringnumpyrepresentation

How to convert a string representation of bytearray to a numpy array?


I have a string like this:

string = "b'\\xf4\\xf0\\xf2\\xef\\xf8\\xf2\\xee'"

So far I have come up with this:

arr = np.array([int(s_num, 16) for s_num in re.findall(r'x([a-f0-9]{2})', string)], dtype=np.uint8)

For large strings this gets really slow. What is the best way to convert the string to a numpy array (of data type np.uint8)? Thanks.


Solution

  • What about:

    from ast import literal_eval
    
    np.frombuffer(literal_eval(string), dtype=np.uint8)
    

    output: array([244, 240, 242, 239, 248, 242, 238], dtype=uint8)