如何将 1 和 0 的行转换为新的 int 列

How to convert row of 1s and 0s to a new int column

我有一个包含 30-40 列的 pandas 数据框,其中包含 1 或 0。如何获得一个 Ints 等于相应字符串的二进制数的新列?例如,第一行应该给出

int('10101',2)
>>> 21
f22 f43 f242 f243 f244
1 0 1 0 1
1 0 1 0 0
0 0 0 0 1
1 0 1 0 1
0 0 0 0 1

我们可以通过基于 DataFrame 的宽度创建一系列 2 的幂来从数学上做到这一点。然后 mul and sum 跨行:

s = pd.Series(reversed([2 ** i for i in range(df.columns.size)]),
              index=df.columns)
df['result'] = df.mul(s, axis=1).sum(axis=1)

df:

   f22  f43  f242  f243  f244  result
0    1    0     1     0     1      21
1    1    0     1     0     0      20
2    0    0     0     0     1       1
3    1    0     1     0     1      21
4    0    0     0     0     1       1

s供参考:

f22     16
f43      8
f242     4
f243     2
f244     1
dtype: int64

设置和导入:

import pandas as pd

df = pd.DataFrame({
    'f22': [1, 1, 0, 1, 0],
    'f43': [0, 0, 0, 0, 0],
    'f242': [1, 1, 0, 1, 0],
    'f243': [0, 0, 0, 0, 0],
    'f244': [1, 0, 1, 1, 1]
})