Dylan Benton
Dylan Benton

Reputation: 1

How can I rewrite a for loop with multiple (nested) if statements to get faster runtimes?

My code currently looks like:

for j in range(len(destined)):
        if destined[j] == 1:
            if den[j,i+1] == 0:
                is_dense = np.hstack((is_dense, j))
            elif den[j,i+1] < den_min:
                is_diffuse = np.hstack((is_diffuse, j))

Looking for help on how to speed this up. This is too slow, since destined and den[:,i+1] are both 1-d arrays with lengths of ~68 million. The conditions and what happens under them isn't important. Any tips for how to do the "for -> if -> if elif" nested structure more efficiently?

Edit: I see how np.hstack is stupid when I'm essentially just using it to append. That's from prior coding attempt where I was actually trying to hstack arrays. My question is more looking for a better way to accomplish what the "for -> if -> if or elif" logic train is accomplishing

Upvotes: 0

Views: 45

Answers (0)

Related Questions