在Pandas或Numpy中,如何使用XOR对一行进行多重缩减,直到所有缩减都被缩减到最后一行

igetnqfo  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(202)

在Pandas或Numpy中,如何多次减少一行,直到所有减少都减少,直到最后一行
好的,我想减少我的B列,以保持每个项目的xoring,直到最后一行:[1,8,6,12,1,2]所以我可以保存它行C
如果尝试使用应用LOO,但是对于大型数据集,这可能变得非常昂贵。有没有人有一个更好的方法,使用一个循环来创建一行又一行,而不是最简单的逻辑来减少这一行?
这里是数据的第二个数字版本如何异或每一个下一行,以获得一个新的列表的答案,并继续向下到最终结果。这是相当缓慢,并正在寻找一个更好的解决方案

A   B  C
0  12   2  0
1  10   6  0
2   2   8  0
3   9  11  0  
4   5  12  0
5   0   5  0
6   4   4  0

for example column B looks like this with a .T transform:

    0   1  2   3   4  5  6
A  12  10  2   9   5  0  4
B   2   6  8  11  12  5  4

so basically is I do these operations:
2 ^ 6. which is 4
6 ^ 8, which is 14
8 ^ 11 which is 3
11 ^ 12 which is 7
5 ^ 4 which is 1. which I store in a separate array because I only want the final result. So now I have

so is have [ 4, 14, 3, 7, 1 ]  and a second array with [1]
4^14 = 10, 14^3=13 3^7=4, 7^1 =1

no I have to keep reducing
[10, 3, 4, 14, 8]
10^3 = 9 3^4 = 7, 4^14=8.  and I manually move the last term to the new array which is now [1, 8]
I do this so forth so my array has all the final results and end up with 

the final result of each iterative reduction: [1  , 8  , 6  ,  12  ,1  ,2] as shown below:

  A   B
[[12  2]
 [10  6] 4   
 [ 2  8] 14  10
 [ 9 11] 3   3   9  
 [ 5 12] 7   4   7    14 
 [ 0  5] 9   14  10   13  3
 [ 4  4] 1   8   6    12  1  2

so that the final out come is the last row in column C

    A   B  C
0  12   2  1
1  10   6  8
2   2   8  6
3   9  11  12  
4   5  12  1
5   0   5  2
6   4   4  0

好的,我想减少我的B列,这样就可以一直向下执行每个项目,直到最后一行:[1,8,6,12,1,2]所以我可以保存它行C
如果尝试使用apply函数和循环,但对于大型数据集,这可能会非常昂贵。有没有人有一个更好的方法,使用一个循环来创建一行又一行,而不是最简单的逻辑来减少这一行?(由于我处理的是非常大的数据集,这只是一个例子)

sg3maiej

sg3maiej1#

这可以用一个单循环来完成。对于性能,您可以使用numba

arr = np.array([2, 6, 8, 11, 12, 5, 4]) # column B
n = len(arr)
results = []

while n > 1:
    results.append(np.bitwise_xor(arr[:n-1], arr[1:]))
    arr = results[-1]
    n = arr.size

holder = np.zeros((len(results), len(results)))
indices = np.triu_indices(len(holder)) # indices of upper triangle of holder
holder[indices] = np.concatenate(results, axis=0)
print(holder[:,-1])
>> [ 1.  8.  6. 12. 15.  2.]

相关问题