【问题标题】:Convert Bitstring (String of 1 and 0s) to numpy array将位串(1 和 0 的字符串)转换为 numpy 数组
【发布时间】:2015-03-17 05:25:44
【问题描述】:

我有一个熊猫数据框,其中包含 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)

【问题讨论】:

    标签: python numpy pandas bitstring


    【解决方案1】:

    对于字符串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字符串的时间->数组转换)

    【讨论】:

    • 请注意 np.array(map(int, s)) 就足够了 - 不需要先构建 list... 此外,它并不完全直观,但 np.fromstring(s, 'i1') - 48 大约快 50%...
    • @JonClements 的性能对于较长的列表来说要差得多——感谢您的注意!
    • @JonClements 我认为这在 Python 3.x 中仍然不正确。现在该 map 返回一个 map 对象(迭代器),您要么必须包裹在 list 中,要么使用 np.fromiter(map(int, s))
    【解决方案2】:

    一种 pandas 方法是在 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])
    

    【讨论】:

      【解决方案3】:

      查看unpackbits

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

      【讨论】:

        猜你喜欢
        • 2010-09-24
        • 2016-03-10
        • 2013-05-05
        • 2021-04-26
        • 2015-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多