Interpret columns of zeros and ones as binary and store as an integer column

后端 未结 3 583
盖世英雄少女心
盖世英雄少女心 2021-01-20 10:00

I have a dataframe of zeros and ones. I want to treat each column as if its values were a binary representation of an integer. What is easiest way to make this conversion?

3条回答
  •  轮回少年
    2021-01-20 10:28

    Similar solution, but more faster:

    print (df.T.dot(1 << np.arange(df.shape[0] - 1, -1, -1)))
    0    12
    1     6
    2    11
    dtype: int64
    

    Timings:

    In [81]: %timeit df.apply(lambda col: int(''.join(str(v) for v in col), 2))
    The slowest run took 5.66 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 264 µs per loop
    
    In [82]: %timeit (df.T*(1 << np.arange(df.shape[0]-1, -1, -1))).sum(axis=1)
    1000 loops, best of 3: 492 µs per loop
    
    In [83]: %timeit (df.T.dot(1 << np.arange(df.shape[0] - 1, -1, -1)))
    The slowest run took 6.14 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 204 µs per loop
    

提交回复
热议问题