输入:
mystr = "100110"
期望的输出numpy数组:
mynumpy == np.array([1, 0, 0, 1, 1, 0])
我已经尝试过:
np.fromstring(mystr, dtype=int, sep='')
但问题是我无法将字符串拆分为每个数字,因此numpy将其视为一个数字。有什么办法可以将我的字符串转换为numpy数组吗?但问题是我无法将字符串拆分为每个数字,因此numpy将其视为一个数字。有什么办法可以将我的字符串转换为numpy数组吗?
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]
你可以把它们当作 ASCII 字符读取,然后减去 48(ASCII 值为 0
)。对于大字符串来说,这应该是最快的方法。
>>> 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倍以上。
ord('0')
代替 48
,显式比隐式更好。 - DerWeh除了以上答案,现在numpy在使用fromstring
时会发出警告: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)
np.fromstring('...', np.int8)
的 grc 的第一种方法要快得多。从(大)字符串创建一个list
是不必要的。 - kyrill