如何转换像' 001100'快点到numpy.array([0,0,1,1,0,0])?

时间:2015-08-22 10:23:56

标签: python numpy types format type-conversion

我有一个由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,所以这种方式非常慢。有没有更好的方法呢?

5 个答案:

答案 0 :(得分:8)

map应该比列表comp快一点:

import  numpy as np

arr = np.array(map(int,'00101'))

有些时间显示它是一串1024个字符:

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

只需在s中调用list并使用dtype = int就更快了:

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

借用此answer,使用fromstring和uint8作为dtype是最快的:

In [54]: timeit  np.fromstring(s, 'int8') - 48
100000 loops, best of 3: 4.54 µs per loop

即使重新绑定名称并更改dtype仍然是最快的:

In [71]: %%timeit
   ....: arr = np.fromstring(s, 'int8') - 48
   ....: arr = arr.astype(int)
   ....: 
100000 loops, best of 3: 6.23 µs per loop

甚至比Ashwini的加入快得多:

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不仅限于1和0,而是适用于由ASCII数字组成的所有字符串。

答案 1 :(得分:2)

我认为列表理解会比你正常的循环方法更快 -

import numpy as np

s = '00101'

np.array([int(c) for c in s])
array([0, 0, 1, 0, 1])

与您的方法进行时间比较(使用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

我进行了重塑,只是为了使两个数组的形状相同,但我认为你真的不需要重新整形,列表理解你获得的数组形状是(<length of string> ,)

答案 2 :(得分:2)

使用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

答案 3 :(得分:1)

使用fromstring方法怎么样?

np.fromstring('1, 2', dtype=int, sep=',')

更多详情here

答案 4 :(得分:0)

np.array(map(lambda x: int(x), s))