Python 将位字符串(1和0的字符串)转换为numpy数组
我有一个包含1列的熊猫数据帧,其中包含一个位字符串,例如Python 将位字符串(1和0的字符串)转换为numpy数组,python,numpy,pandas,bitstring,Python,Numpy,Pandas,Bitstring,我有一个包含1列的熊猫数据帧,其中包含一个位字符串,例如'100100101'。我想把这个字符串转换成一个numpy数组 我该怎么做 编辑: 使用 导致型号出现错误。安装: ValueError: setting an array element with a sequence. 我提出的解决方案适用于我的案例,因为答案是: for bitString in input_table['Bitstring'].values: bits = np.array(map(int, list(b
'100100101'
。我想把这个字符串转换成一个numpy数组
我该怎么做
编辑:
使用
导致型号出现错误。安装:
ValueError: setting an array element with a sequence.
我提出的解决方案适用于我的案例,因为答案是:
for bitString in input_table['Bitstring'].values:
bits = np.array(map(int, list(bitString)))
featureList.append(bits)
features = np.array(featureList)
#....
model.fit(features, lables)
对于字符串s=“100100101”
,您可以至少以两种不同的方式将其转换为numpy数组
第一种是使用numpy的方法。这有点尴尬,因为您必须指定数据类型并减去元素的“基”值
import numpy as np
s = "100100101"
a = np.fromstring(s,'u1') - ord('0')
print a # [1 0 0 1 0 0 1 0 1]
其中,'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]
然后
(这是使用默认的timeit。重复
参数,至少运行3次,每次运行计算运行1M字符串->数组转换的时间)一种方法是调用df列上的apply来执行转换:
In [84]:
df = pd.DataFrame({'bit':['100100101']})
t = df.bit.apply(lambda x: np.array(list(map(int,list(x)))))
t[0]
Out[84]:
array([1, 0, 0, 1, 0, 0, 1, 0, 1])
检查
更一般地说:
>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
[ 7],
[23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
如果您需要超过8位,请查看注意np.array(map(int,s))
就足够了-不需要先构建列表。。。另外,这并不完全直观,但是np.fromstring(s,'i1')-48
大约快了50%。@JonClements的性能对于较长的列表来说要差得多——谢谢你的提示@JonClements我认为这在Python3.x中仍然是不正确的。现在map返回了一个map对象(迭代器),您要么使用list
包装,要么使用np.fromiter(map(int,s))
fromstring: 49.283392424 s
map/array: 2.154540959 s
In [84]:
df = pd.DataFrame({'bit':['100100101']})
t = df.bit.apply(lambda x: np.array(list(map(int,list(x)))))
t[0]
Out[84]:
array([1, 0, 0, 1, 0, 0, 1, 0, 1])
>>> np.unpackbits(np.array([int('010101',2)], dtype=np.uint8))
array([0, 0, 0, 1, 0, 1, 0, 1], dtype=uint8)
>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
[ 7],
[23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)