英文:
Number of different elements for each columns pair
问题
我有一个形状为(n, m)
、dtype为bool
的NumPy数组A
:
array([[ True, False, False],
[ True, True, True],
[False, True, True],
[False, True, False]])
我想要得到形状为(m, m)
、dtype为int
的结果R
:
array([[0, 3, 2],
[3, 0, 1],
[2, 1, 0]])
其中R[i, j]
表示在列i
和列j
中不同元素的数量。例如:
R[0, 0] = (A[:, 0] != A[:, 0]).sum()
R[2, 1] = (A[:, 2] != A[:, 1]).sum()
R[0, 2] = (A[:, 0] != A[:, 2]).sum()
...
是否有办法使用NumPy实现这个目标?
英文:
I have a NumPy array A
of shape (n, m)
and dtype bool
:
array([[ True, False, False],
[ True, True, True],
[False, True, True],
[False, True, False]])
I would like to get the result R
of shape (m, m)
of dtype int
:
array([[0, 3, 2],
[3, 0, 1],
[2, 1, 0]])
where R[i, j]
is the number of elements that are different in columns i
and j
. So, for example:
R[0, 0] = (A[:, 0] != A[:, 0]).sum()
R[2, 1] = (A[:, 2] != A[:, 1]).sum()
R[0, 2] = (A[:, 0] != A[:, 2]).sum()
...
Is there a way to achieve this with NumPy?
Related question: https://stackoverflow.com/questions/76276484/sum-of-element-wise-or-on-columns-triplet
答案1
得分: 2
这是相当简单的,使用一些广播技巧可以完成:
R = (A[:, None, :] != A[:, :, None]).sum(axis=0)
英文:
Yes, this is pretty straightforward with some broadcasting:
R = (A[:, None, :] != A[:, :, None]).sum(axis=0)
答案2
得分: 1
cols = np.arange(A.shape[1])
R = np.sum(A[:,cols.reshape(-1,1)] != A[:,cols.reshape(1,-1)], axis=0)
英文:
Maybe it helps:
cols = np.arange(A.shape[1])
R = np.sum(A[:,cols.reshape(-1,1)] != A[:,cols.reshape(1,-1)], axis=0)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论