我有一个熊猫数据,包含1列,其中包含一串比特,如。'100100101'。我想将这个字符串转换成一个numpy数组。
我怎么能这么做?
编辑:
使用
features = df.bit.apply(lambda x: np.array(list(map(int,list(x)))))
#...
model.fit(features, lables)导致model.fit错误
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)发布于 2015-03-17 05:34:39
对于字符串s = "100100101",可以至少通过两种不同的方式将其转换为numpy数组。
第一种方法是使用numpy的fromstring方法。这有点尴尬,因为您必须指定数据类型并减去元素的“基”值。
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]然后
# To see its a numpy array:
print type(a) # <type 'numpy.ndarray'>
print a[0] # 1
print a[1] # 0
# ...注意,随着输入字符串s长度的增加,第二种方法的缩放效果要比第一种方法差得多。对于小字符串,它是关闭的,但是考虑到90个字符的字符串的timeit结果(我刚刚使用了s * 10):
fromstring: 49.283392424 s
map/array: 2.154540959 s(这是使用默认的timeit.repeat参数,至少3次运行,每次运行计算运行1M字符串->数组转换的时间)
发布于 2015-03-17 09:18:39
熊猫的一种方法是调用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])发布于 2019-02-19 12:19:40
>>> 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)如果您需要超过8位,请查看How to extract the bits of larger numeric Numpy data types
https://stackoverflow.com/questions/29091869
复制相似问题