将字符串转换为numpy数组

时间:2015-01-29 05:44:26

标签: python arrays numpy

我有一个像mystr = "100110"这样的字符串(实际大小要大得多)我想将它转换为像mynumpy = [1, 0, 0, 1, 1, 0], mynumpy.shape = (6,0)这样的numpy数组,我知道numpy有np.fromstring(mystr, dtype=int, sep='')但问题是我无法将我的字符串拆分为它的每个数字,因此numpy将其作为一个数字。任何想法如何将我的字符串转换为numpy数组?

3 个答案:

答案 0 :(得分:24)

list可以帮助您做到这一点。

import numpy as np

mystr = "100110"
print np.array(list(mystr))
# ['1' '0' '0' '1' '1' '0']

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

print np.array(list(mystr), dtype=int)
# [1 0 0 1 1 0]

答案 1 :(得分:18)

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

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

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

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

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

答案 2 :(得分:3)

添加到上述答案后,当您使用fromstring时numpy会给出弃用警告
DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
更好的选择是使用fromiter。它的执行速度快一倍。这就是我在jupyter笔记本中得到的-

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)
相关问题