简体   繁体   English

如何在for循环中追加到空数据框

[英]how to append to empty dataframe in for loop

I'm using pandas as pd and python 2.7 我正在将熊猫用作pd和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)

You are resetting the list to be empty at the beginning of each for loop. 您将在每个for循环的开始将列表重置为空。 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). 此外,看起来您可能正在破坏results因为您两次将其用作变量名(每个循环一次)。 I would suggest changing that too! 我建议也改变它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM