我有一个由0和1组成的字符串,例如'00101'
。我想将其转换为numpy数组numpy.array([0,0,1,0,1])
。
我使用for
循环来实现:
import numpy as np
X = np.zeros((1,5),int)
S = '00101'
for i in xrange(5):
X[0][i] = int(S[i])
但是由于我有很多字符串,每个字符串的长度都是1024,这种方法非常慢。有没有更好的方法来做到这一点?
我有一个由0和1组成的字符串,例如'00101'
。我想将其转换为numpy数组numpy.array([0,0,1,0,1])
。
我使用for
循环来实现:
import numpy as np
X = np.zeros((1,5),int)
S = '00101'
for i in xrange(5):
X[0][i] = int(S[i])
但是由于我有很多字符串,每个字符串的长度都是1024,这种方法非常慢。有没有更好的方法来做到这一点?
使用map函数比使用列表解析略快一些:
import numpy as np
arr = np.array(map(int,'00101'))
In [12]: timeit np.array([int(c) for c in s])
1000 loops, best of 3: 422 µs per loop
In [13]: timeit np.array(map(int,s))
1000 loops, best of 3: 389 µs per loop
只需要在使用dtype=int时对s列表进行调用即可提高速度:
In [20]: timeit np.array(list(s), dtype=int)
1000 loops, best of 3: 329 µs per loop
使用fromiter函数并传递dtype=int
参数可以再次提高速度:
In [21]: timeit np.fromiter(s,dtype=int)
1000 loops, best of 3: 289 µs per loop
借鉴这个答案,使用fromstring和uint8作为dtype是最快的:
In [54]: timeit np.fromstring(s, 'int8') - 48
100000 loops, best of 3: 4.54 µs per loop
即使重新绑定名称并更改数据类型,仍然是目前最快的方法:
In [71]: %%timeit
....: arr = np.fromstring(s, 'int8') - 48
....: arr = arr.astype(int)
....:
100000 loops, best of 3: 6.23 µs per loop
In [76]: timeit np.fromstring(' '.join(s), sep=' ', dtype=int)
10000 loops, best of 3: 62.6 µs per loop
正如@Unutbu所评论的那样,np.fromstring(s, 'int8') - 48
不仅限于二进制,它也可以用于由ASCII数字组成的任何字符串。
import numpy as np
s = '00101'
np.array([int(c) for c in s])
array([0, 0, 1, 0, 1])
使用Timeit(对于长度为1024的字符串)与您的方法进行比较-
In [41]: S = '0' * 512 + '1' * 512
In [43]: %%timeit
....: X = np.zeros((1,len(S)),int)
....: for i in range(len(S)):
....: X[0][i] = int(S[i])
....:
1000 loops, best of 3: 854 µs per loop
In [45]: %%timeit
....: Y = np.array([int(c) for c in S]).reshape((1,len(S)))
....:
1000 loops, best of 3: 339 µs per loop
我进行了reshape,只是为了使两个数组具有相同的形状,但我认为你实际上不需要reshape,在列表推导中,你得到的数组形状是(<字符串长度> ,)
使用numpy.fromstring
函数:
>>> s = '00101'
>>> np.fromstring(' '.join(s), sep=' ', dtype=int)
array([0, 0, 1, 0, 1])
>>> s = '00101' * 1000
>>> %timeit np.fromiter(s, dtype=int)
100 loops, best of 3: 2.33 ms per loop
>>> %timeit np.fromstring(' '.join(s), sep=' ', dtype=int)
1000 loops, best of 3: 499 µs per loop
np.array(map(lambda x: int(x), s))
np.array(map(lambda x: int(x),s))
lambda
是用来做什么的?只需使用int
。 - Eli Korvigo