简体   繁体   English

如何使用 python 翻转/反转列中所有二进制数的第 n 位

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

I created a dataframe where the last column shows the binary conversion of the previous column.我创建了一个 dataframe ,其中最后一列显示了前一列的二进制转换。 Now I want flip the last one/two binary bits from every binary numbers of that column(R).现在我想从该列(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.以下是我的示例代码和 O/P。 For example, for the 1st row, I want the binary number as 001101 (from 001100) after fliping the last bit.例如,对于第一行,我希望在翻转最后一位后二进制数为 001101(来自 001100)。

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

One way is to use pandas string slicing一种方法是使用pandas 字符串切片

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM