Devin Liner
Devin Liner

Reputation: 449

how to append to empty dataframe in for loop

I'm using pandas as pd and python 2.7

I have a bunch of queries and each query is returning serial numbers. Then I'm using that serial number in a bunch more queries. I want to append all the results to a list. When I append to an empty list, it just returns nothing. I don't know what I'm doing wrong.

 for query in list_of_queries:
     results  = pd.read_sql_query(query,connection,index_col=None)
     for serial_number in results['SerialNumbers']:
        a = []
        new_query = """ SELECT * FROM blah b where b.SerialNumber = '{}' """
        new_query = new_query.format(serial_number)
        results = pd.read_sql_query(new_query,connection,index_col = None)
        a.append(results)

Upvotes: 0

Views: 910

Answers (1)

AetherUnbound
AetherUnbound

Reputation: 1744

You are resetting the list to be empty at the beginning of each for loop. This should be:

a = []
for serial_number in results['SerialNumbers']:        
    new_query = """ SELECT * FROM blah b where b.SerialNumber = '{}' """
    new_query = new_query.format(serial_number)
    results = pd.read_sql_query(new_query,connection,index_col = None)
    a.append(results)
# 'a' will now have all the results

Furthermore, it looks like you might be clobbering results because you use it as a variable name twice (once in each loop). I would suggest changing that too!

Upvotes: 1

Related Questions