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
563 views
in Technique[技术] by (71.8m points)

python - Comparing two numpy arrays and removing elements

I have been going through several solutions, but I am not able to find a solution I need.

I have two numpy arrays. Let's take a small example here.

x = [1,2,3,4,5,6,7,8,9]
y = [3,4,5]

I want to compare x and y, and remove those values of x that are in y.

So I expect my final_x to be

final_x = [1,2,6,7,8,9]

I found out that np.in1d returns a boolean array the same length as x that is True where an element of x is in y and False otherwise. But how do I use it, if not any other method to get my final_x.??

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you really do have numpy arrays then you can use numpy.setdiff1d as below

import numpy as np

x = np.array([1,2,3,4,5,6,7,8,9])
y = np.array([3,4,5])

z = np.setdiff1d(x, y)
# array([1, 2, 6, 7, 8, 9])

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

...