1

Below is my code which is taking a long time to execute. How can I implement it in a list comprehension in Python to improve speed and efficiency?

buildings=[]
for bi in range(1449):
    for si in range (16):
        for m in range(3):
            a= train[(train['building_id']==bi)&(train['site_id']==si)&(train['meter']==m)]
            if not a.empty:

                buildings.append(a.values)
2
  • 3
    Share your sample data. Commented Nov 28, 2019 at 6:34
  • A list comprehension is just syntactic sugar for a loop. Their advantage is one of readability, not speed. 1449*16*3 is still 69552, even if you hide the nested loops in an equivalent comprehension. Commented Dec 4, 2019 at 18:05

1 Answer 1

1

Hard to tell if this is correct without your sample data, but this should work theoretically:

buildings = [
             x for x in
                 [
                 train[(train['building_id']==bi)&(train['site_id']==si)&(train['meter']==m)].values
                 for bi in range(1449)
                 for si in range(16)
                 for m in range(3)
                 ]
            if not x.empty
            ]
Sign up to request clarification or add additional context in comments.

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.