-1

What is the fastest way of getting specific indexes from one list and remove from other list python.

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
b = [nan, 'gfdg', 54.0, nan, 54.0, nan, 'wre', nan, 54, nan]

I want to remove nan from list 'b' and similar index from list 'a' such that the expected result should be:

a = ['b', 'c',  'e',  'g',  'i' ]
b = ['gfdg', 54.0, 54.0, 'wre', 54]

2 Answers 2

1

You can try:

a,b = zip(*(t for t in zip(a,b) if t[1] != nan))

Use a = list(a) and b = list(b) afterwards if you want lists instead of tuples.


>>> a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> b = [nan, 'gfdg', 54.0, nan, 54.0, nan, 'wre', nan, 54, nan]
>>> 
>>> a,b = zip(*(t for t in zip(a,b) if t[1] != nan))
>>> a
('b', 'c', 'e', 'g', 'i')
>>> b
('gfdg', 54.0, 54.0, 'wre', 54)
1

You can use list-comprehension to do that, for example:

a = [a[i] for i in range(len(b)) if b[i] != nan]
b = [x for x in b if x != nan]

output:

>>> a
['b', 'c', 'e', 'g', 'i']
>>> b
['gfdg', 54.0, 54.0, 'wre', 54]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.