首页 > 解决方案 > Numpy 2d 设置差异

问题描述

在 numpy 中是否可以在这两个数组之间产生差异:

[[0 0 0 0 1 1 1 1 2 2 2 2]
 [0 1 2 3 0 1 2 3 0 1 2 3]]


[[0 0 0 0 1 1 1 2 2 2]
 [0 1 2 3 0 2 3 0 1 2]]

有这个结果

[[1 2]
 [1 3]]

?

标签: pythonpandasnumpy

解决方案


这是一种方式。您也可以使用numpy.unique类似的解决方案(在 v1.13+ 中更容易,请参阅Find unique rows in numpy.array),但如果性能不是问题,您可以使用set.

import numpy as np

A = np.array([[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2],
              [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]])

B = np.array([[0, 0, 0, 0, 1, 1, 1, 2, 2, 2],
              [0, 1, 2, 3, 0, 2, 3, 0, 1, 2]])

res = np.array(list(set(map(tuple, A.T)) - set(map(tuple, B.T)))).T

array([[2, 1],
       [3, 1]])

推荐阅读