I loop through a list of tables and dates from a database to gather data. Something like this:
df_list = []
for table in table_list:
for date in required_date_range:
query = 'SELECT * FROM {} WHERE row_date = {};'.format(table, date)
df = pd.read_sql_query(sql=query, con=engine)
df_list.append(df)
result = pd.concat(df_list)
Is there a way to put a loop like that into a list comprehension? Is it even worth it?
I found some example code from https://tomaugspurger.github.io/modern-4-performance.html
files = glob.glob('weather/*.csv')
weather_dfs = [pd.read_csv(fp, names=columns) for fp in files]
weather = pd.concat(weather_dfs)
It looks better and the charts show it performs better but I just can't seem to wrap my head around it when I try to adjust my own code.
Edit-
It seems to work if I make a list of the queries instead. Is there a way to get that initial for loop and .format into a list comprehension as well?
for table in table_list:
for date in required_date_range:
queries = ['SELECT * FROM {} WHERE row_date = {};'.format(table, date)]
dfs = [pd.read_sql_query(query, con=pg_engine) for query in queries]