Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - find and delete from more-dimensional numpy array

I have two numpy-arrays:

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]])

I want to delete all the columns from p_a_colors that are in p_rem, so I get:

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

I think, something should work like

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

but I just don't get the axis or [:] right.

I know, that

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)

would work, but I am trying to avoid (python)loops, because I also want the performance right.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is how I would do it:

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]])

You need to do the void dtype thing so that numpy compares rows as a whole. After that using the built-in set routines seems like the obvious way to go.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...