Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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,

like image 506
bigCow Avatar asked Sep 26 '13 01:09

bigCow


2 Answers

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)]
like image 180
abarnert Avatar answered Oct 22 '22 10:10

abarnert


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.

like image 35
Dylan Lawrence Avatar answered Oct 22 '22 10:10

Dylan Lawrence