6

我有两个 numpy 数组:

p_a_colors=np.array([[0,0,0],
                     [0,2,0],
                     [119,103,82],
                     [122,122,122],
                     [122,122,122],
                     [3,2,4]])

p_rem = np.array([[119,103,82],
                     [122,122,122]])

我想从 p_rem 中的 p_a_colors 中删除所有列,所以我得到:

p_r_colors=np.array([[0,0,0],
                    [0,2,0],
                    [3,2,4]])

我认为,应该像

p_r_colors= np.delete(p_a_colors, np.where(np.all(p_a_colors==p_rem, axis=0)),0)

但我只是没有得到正确的轴或 [:]。

我知道

p_r_colors=copy.deepcopy(p_a_colors)
for i in range(len(p_rem)):
    p_r_colors= np.delete(p_r_colors, np.where(np.all(p_r_colors==p_rem[i], axis=-1)),0)

会工作,但我试图避免(python)循环,因为我也希望性能正确。

4

3 回答 3

7

我会这样做:

dtype = np.dtype((np.void, (p_a_colors.shape[1] * 
                            p_a_colors.dtype.itemsize)))
mask = np.in1d(p_a_colors.view(dtype), p_rem.view(dtype))
p_r_colors = p_a_colors[~mask]

>>> p_r_colors
array([[0, 0, 0],
       [0, 2, 0],
       [3, 2, 4]])

您需要执行 void dtype 操作,以便 numpy 将行作为一个整体进行比较。在那之后,使用内置的设置例程似乎是显而易见的方法。

于 2013-05-30T15:39:30.907 回答
1

您弄错了索引。该表达式的p_a_colors==p_rem计算结果为一个空数组,因为这两个数组永远不会相等(它们具有不同的形状!)。如果要使用np.delete,则需要更正确的索引列表。

另一方面,这可以通过索引更容易地完成:

>>> idx = np.array([p_a_colors[i] not in p_rem for i in
                    range(p_a_colors.shape[0])], dtype='bool')
>>> p_a_colors[idx]
array([[0, 0, 0],
       [0, 2, 0],
       [3, 2, 4]])

或者,受@Jaime 建议的启发,您还可以np.in1d在一行中创建索引:

>>> idx = ~np.all(np.in1d(p_a_colors, p_rem).reshape(p_a_colors.shape), 
                  axis=1)
>>> p_a_colors[idx]
array([[0, 0, 0],
       [0, 2, 0],
       [3, 2, 4]])

如果必须使用np.delete,只需将索引列表 frombool转换为序列:

>>> idx = np.array([p_a_colors[i] in p_rem for i in 
                          range(p_a_colors.shape[0])])
>>> idx = np.arange(p_a_colors.shape[0])[idx]
>>> np.delete(p_a_colors, idx, axis=0)
array([[0, 0, 0],
       [0, 2, 0],
       [3, 2, 4]])
于 2013-05-30T15:38:37.613 回答
1

很丑,但是

tmp = reduce(lambda x, y: x |  np.all(p_a_colors == y, axis=-1), p_rem, np.zeros(p_a_colors.shape[:1], dtype=np.bool))

indices = np.where(tmp)[0]

np.delete(p_a_colors, indices, axis=0)

(编辑:更正)

>>> tmp = reduce(lambda x, y: x |  np.all(p_a_colors == y, axis=-1), p_rem, np.zeros(p_a_colors.shape[:1], dtype=np.bool))
>>> 
>>> indices = np.where(tmp)[0]
>>> 
>>> np.delete(p_a_colors, indices, axis=0)
array([[0, 0, 0],
       [0, 2, 0],
       [3, 2, 4]])
>>> 
于 2013-05-30T15:29:30.430 回答