1

I have a Python list (numpy array) and another list which contains the indices for the location of values from the first array which I want to keep.

Is there a Pythonic way to do this? I know numpy.delete, but I want to keep the elements and not delete them.

5
  • 2
    What have you tried? What's your existing solution that you think that may not be "Pythonic" enough? Commented Sep 15, 2018 at 6:21
  • @woozyking option 1: iterating over the main array and checking if that index is there in the second array or not (we can convert the second list to a map for O(1) lookup). option 2: make a copy of first array and then deleting using numpy.delete and then taking the difference between the original list and new (smaller) list - but this will not retain the original order. Commented Sep 15, 2018 at 6:26
  • That's wonderful to have more than one option. However it'd be even better for you to actually demonstrate them as (sample) code so others can help you more effectively. Commented Sep 15, 2018 at 6:30
  • @woozyking I'm not sure if a (sample) code will help. My question is not about how to efficiently implement what I wrote, but if there's a fundamentally different way to achieve this (perhaps in a single line) which I am missing. Commented Sep 15, 2018 at 6:34
  • I'm not sure what your starting conditions are. Do you want to act on a Python list or a numpy.array? Obviously, it cannot be both at the same time. Commented Sep 15, 2018 at 11:20

3 Answers 3

2

The most pythonic way is probably also the most straightforward one:

a = np.array([2,5,6,3,6,3,45,6])
b = [0,3,4,7] # indices that you need to keep
c = a[b]

or, if you do not need a any longer:

a = a[b]
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a new list with the values that you want to keep.

a = np.array([2,5,6,3,6,3,45,6])
b = [0,3,4,7] #indices that yo need to keep
c = [a[i] for i in b]

2 Comments

Well, this is more cleaner than any of the approaches I mentioned above. Thanks for this!
Why not just a[b]? Much more efficient to use numpy indexing if working with numpy arrays
1

Why don't you use just c=a[b] as this is the Python way to take the values from array a.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.