Convert string to numpy array

后端 未结 3 1217
死守一世寂寞
死守一世寂寞 2021-01-01 13:35

I have a string like mystr = \"100110\" (the real size is much bigger) I want to convert it to numpy array like mynumpy = [1, 0, 0, 1, 1, 0], mynumpy.shap

3条回答
  •  一个人的身影
    2021-01-01 14:35

    You could read them as ASCII characters then subtract 48 (the ASCII value of 0). This should be the fastest way for large strings.

    >>> np.fromstring("100110", np.int8) - 48
    array([1, 0, 0, 1, 1, 0], dtype=int8)
    

    Alternatively, you could convert the string to a list of integers first:

    >>> np.array(map(int, "100110"))
    array([1, 0, 0, 1, 1, 0])
    

    Edit: I did some quick timing and the first method is over 100x faster than converting it to a list first.

提交回复
热议问题