Search code examples
pythonpandasxor

Flip a boolean based on another python dataframe?


I have two columns in a dataframe "Original" and "Flipper". I want whenever "Flipper" has a value of 1, that a new column "Output" has the opposite of "Original", and when it has a value of 0 then the value of "Original" is put into "Output"

Original Flipper Output
0          0        0
0          1        1
1          0        1
1          1        0

This is just a XOR gate, but I don't think that writing it as a XOR gate will be very maintainable , nor do I know how.

What is the way to write this code so that the two columns "Original" and "Flipper" can generate "Output" in a readable manner?


Solution

  • I found three methods for doing this task:

    Method 1: Multiply not Equal

    %timeit 1 * (df['Original'] != df['Flipper'])
    340 µs ± 42.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

    Method 2: XOR

    %timeit df["Original"]^df["Flipper"]
    160 µs ± 22.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    

    Method 3: np.logical_xor

    %timeit np.logical_xor(df["Original"],df["Flipper"])
    360 µs ± 1.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)