Skip to content
Advertisement

multiple for in python query loop and save them

need to save them into different data frames

query = '''select name 
from my_table
where class = {}
and student_number > {}
and student_number <= {} +10
group by name'''
inputs = list(range(0, 100,10))
classes = [1,2,3,4]

the expected result is running these batches for each class individually. e.g df_class1, df_class2 df_class3, df_class4

query = '''
select name  from my_table where class = {} and student_number > 
{} and student_number <= {} +50 group by name'''  
inputs = list(range(0, 100,10)) 
classes = [1,2,3,4] 
not sure on this part ##for i in inputs:     for c in classes: query.format(c, i, i)##

results = pd.DataFrame() for input, query in queries.items(): 
res = my_db.execute(query)     
results = results.append(pd.DataFrame(res))

each results as sth like ;df_class1, df_class2 df_class3, df_class4

Advertisement

Answer

You can use formatted string to save the resultant dataframe for each iteration.

inputs = list(range(0, 100,10)) 
classes = [1,2,3,4]
for i in inputs:     
    for c in classes: 
        query.format(c, i, i)
        res = my_db.execute(query)
        df = pd.DataFrame(res)
        df.to_csv(f'result_{i}_{c}.csv') 
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement