bigCow
bigCow

Reputation: 303

python: How to remove values from 2 lists based on what's in 1 list

I have 2 lists of numbers, one called xVar and the other called yVar. I will use these 2 elements to plot X and Y values on a graph. They both have the same number of elements.

Normally, I would just plot

ax.scatter(xVar,yVar,s=2,color='tomato');

I want to remove data from yVar that are over a certain value, for example all data that have a yVar value over 100, but I also want to remove the associated xVar value. Can somebody suggest a way to create 2 new variables that remove all values in yVar over 100 and the xVar values associated with them? Then I can just substitute xVar & yVar in my plotting line to the new variables.

Thanks again All,

Upvotes: 7

Views: 4046

Answers (3)

abarnert
abarnert

Reputation: 366073

Whenever you want to do something to the corresponding values of two (or more) lists, that's what zip is for. It gives you one list, of the corresponding values for each index.

So, in this case, zip the two lists together, then filtered the zipped list, then unzip them (with zip again, as the documentation explains):

xVar, yVar = zip(*((x, y) for x, y in zip(xVar, yVar) if y <= 100))

If this is confusing, let me show it step by step:

>>> xVar = [1, 200, 300, 10]
>>> yVar = [150, 100, 50, 200]
>>> xyVar = zip(xVar, yVar)
>>> xyVar
[(1, 150), (200, 100), (300, 50), (10, 500)]
>>> xyFiltered = [(x, y) for x, y in xyVar if y <= 100]
>>> xyFiltered
[(200, 100), (300, 50)]
>>> xVar, yVar = zip(*xyFiltered)
[(200, 300), (100, 50)]

Upvotes: 15

sashkello
sashkello

Reputation: 17871

Find indices which correspond to data you want to retain:

ind = [i for i in range(len(yVar)) if yVar[i] < 100]

And use only those points:

yVar = [yVar[i] for i in ind]
xVar = [xVar[i] for i in ind]

Upvotes: 0

Dylan Lawrence
Dylan Lawrence

Reputation: 1533

Without writing the code, find the index for the y you want to remove, save the index, remove the y value, then remove the x value at the same index number.

Upvotes: 1

Related Questions