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

Kyle Hunter
  • 257
  • 3
  • 10

1 Answers1

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]]
Community
  • 1
  • 1
user3684792
  • 2,542
  • 2
  • 18
  • 23
  • 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? – Kyle Hunter Apr 15 '16 at 14:09
  • 1
    even though the syntax is similar, the list comprehension I have used is not actually a for loop – user3684792 Apr 15 '16 at 14:14
  • Yeah, just noticed that. It's significantly faster that my original for loop. Thanks a lot for your help! – Kyle Hunter Apr 15 '16 at 14:16
  • 1
    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. – hpaulj Apr 15 '16 at 15:49