Search code examples
pythonpandasnumpyxor

How do xor a dataframe slice with the next num and insert the answer in column 'dr'


Ok I have this data frame which you notice is names solve and I'm using a slice of 4

In [13147]: solve[::4]
Out[13147]: 
    rst  dr
0     1   0
4     3   0
8     7   0
12    5   0
16   14   0
20   12   0
24    4   0
28    4   0
32    4   0
36    3   0
40    3   0
44    5   0
48    5   0
52   13   0
56    3   0
60    1   0

What I want is to in column 'rst' xor 1 by 3 and get 2 (1^3=2). then I want to do 3^7 = 4, I want to put those in the corresponding spots in dr. so solve.loc[0:, ('dr')] = 2, and solve.loc[4:, ('dr')] = 4. My current method is tedious and not automatic, here is what I'm doing:

In [13150]: np.array(solve.loc[::4, ('rst')]) ^ np.array(solve.loc[4::4, ('rst')])
ValueError: operands could not be broadcast together with shapes (16,) (15,) 

which is resolved with:

In [13159]: wutwut = np.array(solve.loc[::4, ('rst')])[:15] ^ np.array(solve.loc[4::4, ('rst')])
Out[13159]: 
array([ 2,  4,  2, 11,  2,  8,  0,  0,  7,  0,  6,  0,  8, 14,  2],
      dtype=int8)

and then putting the values back into solve.loc['dr'] is an issue because I have to bust a length in manually like:

solve.loc[:56:4, ('dr')] = wutwut

see I have to manually set the length, is there a more automatic way

As you can see this is tedious and not practical because I'm working with different and changing lengths and I need a more automatic best practice cast for this. I'm looking for some suggestions and thanks in advance. Also I have more advanced use cases where is xor between columns so if anyone has strategies for that it will help me down the road as well


Solution

  • Lets use loc for indexing and automatic value assignment

    s = solve.loc[::4, 'rst']
    solve.loc[s.index[:-1], 'dr'] = s[:-1].values ^ s[1:].values
    

        rst  dr
    0     1   2
    4     3   4
    8     7   2
    12    5  11
    16   14   2
    20   12   8
    24    4   0
    28    4   0
    32    4   7
    36    3   0
    40    3   6
    44    5   0
    48    5   8
    52   13  14
    56    3   2
    60    1   0