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

后端 未结 3 585
盖世英雄少女心
盖世英雄少女心 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:41

    You can create a string from the column values and then use int(binary_string, base=2) to convert to integer:

    df.apply(lambda col: int(''.join(str(v) for v in col), 2))
    Out[6]: 
    0    12
    1     6
    2    11
    dtype: int64
    

    Not sure about efficiency, multiplying by the relevant powers of 2 then summing probably takes better advantage of fast numpy operations, this is probably more convenient though.

提交回复
热议问题