2

So i'm working on optimizing some python code by using numpy arrays instead of for each loops. Is there any way to access fields from a class during slicing of a numpy array?

class foo:

    the_int = 0

    def __init__(self, i):
        self.bar = i

one, two = foo(5), foo(10)
ar = array([one, two])

int_array = ar[0:2].the_int

#I want int_array = [5, 10]

If that isn't possible in that manner, how would I efficiently generate my "int_array" variable without using a for each loop to loop through "ar", gather "the_int" from each entry?

Thanks, Kyle

1 Answer 1

2

Why are you using a numpy array to store PyObjects? You won't get the performance improvement you think. See here.

Using a list, you can use a list comprehension instead:

class foo:

    the_int = 0

    def __init__(self, i):
        self.bar = i

one, two = foo(5), foo(10)

ar = [one, two]

int_array = [i.bar for i in ar[0:2]]
Sign up to request clarification or add additional context in comments.

4 Comments

Ahh, that makes sense. Didn't realize that numpy arrays shouldn't store objects. So there's no way with objects to avoid the for each loop?
even though the syntax is similar, the list comprehension I have used is not actually a for loop
Yeah, just noticed that. It's significantly faster that my original for loop. Thanks a lot for your help!
Something, for loop or otherwise, has to query each object (or the list or array) for its bar attribute. Your object has been coded in Python, so that query is a Python operation.

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.