How do I create a numpy array from string?

前端 未结 3 1300
我在风中等你
我在风中等你 2021-02-08 11:53

I have a file reader that reads n bytes from a file and returns a string of chars representing that (binary) data. I want to read up n bytes into a numpy array

相关标签:
3条回答
  • 2021-02-08 12:26

    You can do this directly with numpy.fromstring:

    import numpy as np
    s = '\x01\x05\x03\xff'
    a = np.fromstring(s, dtype='uint8')
    

    Once completing this, a is array([ 1, 5, 3, 255]) and you can use the regular scipy/numpy FFT routines.

    0 讨论(0)
  • 2021-02-08 12:33
    >>> '\x01\x05\x03\xff'
    '\x01\x05\x03\xff'
    >>> map(ord, '\x01\x05\x03\xff')
    [1, 5, 3, 255]
    >>> numpy.array(map(ord, '\x01\x05\x03\xff'))
    array([  1,   5,   3, 255])
    
    0 讨论(0)
  • 2021-02-08 12:38

    Without knowing what you've got coming in it's tough, but if it were comma delimited integers you could do something like this:

    myInts = map(int, myString.split(','))
    
    0 讨论(0)
提交回复
热议问题