How to flip/inverse nth bit of all binary numbers in a column using python

Viewed 46

I created a dataframe where the last column shows the binary conversion of the previous column. Now I want flip the last one/two binary bits from every binary numbers of that column(R). I want flip that specific binary bit in a way that it does not affect the other bits.

How can I do that? Following is my sample code and O/P. For example, for the 1st row, I want the binary number as 001101 (from 001100) after fliping the last bit.

df = pd.DataFrame(np.random.randint(1,3,size=(10, 8)), columns=list('ABCDEFGH'))
df['Q']=df.sum(axis=1)
df['R']=df.Q.apply(lambda x: format(int(x), '06b'))

O/P:

   A  B  C  D  E  F  G  H   Q       R
0  2  2  1  1  1  1  2  2  12  001100
1  2  1  1  1  1  1  2  1  10  001010
2  2  2  1  2  2  2  1  2  14  001110
3  1  2  2  2  1  1  2  1  12  001100
4  1  2  2  1  1  2  1  1  11  001011
5  2  1  1  2  1  1  2  1  11  001011
6  1  2  2  1  1  2  1  2  12  001100
7  2  2  1  2  1  1  1  1  11  001011
8  2  1  2  2  2  2  2  1  14  001110
9  1  2  1  1  1  2  2  2  12  001100
1 Answers

One way is to use pandas string slicing

df = pd.DataFrame(np.random.randint(1,3,size=(10, 8)), columns=list('ABCDEFGH'))
df['Q']=df.sum(axis=1)
df['R']=df.Q.apply(lambda x: format(int(x), '06b'))
print("Before:\n", df)
df.R = df.R.str.slice(stop=-1) + (1 - df.R.str.slice(start=-1).astype(int)).astype(str)
print("\nAfter:\n", df)

Output:

 Before:
    A  B  C  D  E  F  G  H   Q       R
0  1  1  2  2  1  1  1  2  11  001011
1  2  2  1  2  1  1  1  2  12  001100
2  1  1  2  1  1  1  1  1   9  001001
3  2  1  2  2  1  2  2  1  13  001101
4  1  1  2  2  1  1  1  2  11  001011
5  2  2  2  1  2  2  2  2  15  001111
6  1  2  1  2  2  1  2  1  12  001100
7  1  1  1  1  1  2  2  2  11  001011
8  1  1  1  2  1  2  1  1  10  001010
9  2  2  1  2  2  1  1  1  12  001100

After:
    A  B  C  D  E  F  G  H   Q       R
0  1  1  2  2  1  1  1  2  11  001010
1  2  2  1  2  1  1  1  2  12  001101
2  1  1  2  1  1  1  1  1   9  001000
3  2  1  2  2  1  2  2  1  13  001100
4  1  1  2  2  1  1  1  2  11  001010
5  2  2  2  1  2  2  2  2  15  001110
6  1  2  1  2  2  1  2  1  12  001101
7  1  1  1  1  1  2  2  2  11  001010
8  1  1  1  2  1  2  1  1  10  001011
9  2  2  1  2  2  1  1  1  12  001101
Related