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

Time:10-22

I have a pandas dataframe with 30-40 columns, which contain 1 or 0. How to get a new column with Ints equal to the binary number of the correspondent string? For example, the first row should give

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

CodePudding user response:

First apply combines rows as strings, second converts them to int.

df["new_column"] = df.apply(lambda x:"".join(x.astype(str)),axis=1).apply(lambda x:int(x,2))

CodePudding user response:

We can do it mathematically, by creating a Series of powers of 2 based on the width of the DataFrame. Then mul and sum across the rows:

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 for reference:

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

Setup and imports:

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]
})
  • Related