将字符串转换为numpy数组

Am1*_*3zA 17 python arrays numpy

我有一个字符串mystr = "100110"(真正的大小更大)我想将它转换为numpy数组mynumpy = [1, 0, 0, 1, 1, 0], mynumpy.shape = (6,0),我知道numpy np.fromstring(mystr, dtype=int, sep='') 还有问题是我不能将我的字符串拆分为它的每一个数字,所以numpy将其视为一个号码.任何想法如何将我的字符串转换为numpy数组?

dra*_*fly 31

list 可以帮你做到这一点.

import numpy as np

mystr = "100110"
print np.array(list(mystr))
# ['1' '0' '0' '1' '1' '0']
Run Code Online (Sandbox Code Playgroud)

如果你想得到数字而不是字符串:

print np.array(list(mystr), dtype=int)
# [1 0 0 1 1 0]
Run Code Online (Sandbox Code Playgroud)


grc*_*grc 19

您可以将它们读作ASCII字符,然后减去48(ASCII值0).这应该是大字符串的最快方法.

>>> np.fromstring("100110", np.int8) - 48
array([1, 0, 0, 1, 1, 0], dtype=int8)
Run Code Online (Sandbox Code Playgroud)

或者,您可以先将字符串转换为整数列表:

>>> np.array(map(int, "100110"))
array([1, 0, 0, 1, 1, 0])
Run Code Online (Sandbox Code Playgroud)

编辑:我做了一些快速计时,第一种方法比首先将其转换为列表快100多倍.

  • 我强烈建议您使用`ord('0')`而不是`48`。显式比隐式更好。 (3认同)

Hru*_*mal 9

添加到上述答案中,numpy 现在在您使用fromstring
DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead.
更好的选择是使用fromiter. 它的执行速度是原来的两倍。这是我在 jupyter notebook 中得到的 -

import numpy as np
mystr = "100110"

np.fromiter(mystr, dtype=int)
>> array([1, 0, 0, 1, 1, 0])

# Time comparison
%timeit np.array(list(mystr), dtype=int)
>> 3.5 µs ± 627 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.fromstring(mystr, np.int8) - 48
>> 3.52 µs ± 508 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.fromiter(mystr, dtype=int)
1.75 µs ± 133 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Run Code Online (Sandbox Code Playgroud)