对于一个字符串s = "100100101"
,您可以通过至少两种不同的方式将其转换为 numpy 数组。
第一个使用 numpy 的fromstring http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html方法。这有点尴尬,因为您必须指定数据类型并减去元素的“基”值。
import numpy as np
s = "100100101"
a = np.fromstring(s,'u1') - ord('0')
print a # [1 0 0 1 0 0 1 0 1]
Where 'u1'
是数据类型并且ord('0')
用于从每个元素中减去“基”值。
第二种方法是将每个字符串元素转换为整数(因为字符串是可迭代的),然后将该列表传递到np.array
:
import numpy as np
s = "100100101"
b = np.array(map(int, s))
print b # [1 0 0 1 0 0 1 0 1]
Then
# To see its a numpy array:
print type(a) # <type 'numpy.ndarray'>
print a[0] # 1
print a[1] # 0
# ...
请注意,作为输入字符串的长度,第二种方法的扩展性明显比第一种方法差s
增加。对于小字符串,它很接近,但请考虑timeit https://docs.python.org/2/library/timeit.html90 个字符的字符串的结果(我刚刚使用s * 10
):
fromstring: 49.283392424 s
map/array: 2.154540959 s
(这是使用默认的timeit.repeat
参数,最少 3 次运行,每次运行计算运行 1M 字符串->数组转换的时间)