某些背景
我写了一个 for 循环,在其中尝试附加多个数据帧。在每次迭代中,都会创建一个新的数据框,我想将该数据框附加到现有数据框上。
在每次迭代中,我都是从postgres数据库中提取数据
下面是我的代码
temp = my_base_dataframe
df = pd.DataFrame()
df1 = pd.DataFrame()
for index, row in temp.iterrows():
#Part 1 Get min, max timestamp for each ID
ID = row['recorded_id']
min_time = row['min']
max_time = row['max']
#Part2 Query redshift with parameters from part 1
if df.empty:
df = pd.read_sql_query("SELECT key, tag name, description, datetime, tag_value FROM (SELECT tag_value,datetime, data_key, dim_facility_key FROM pub.values_numeric WHERE datetime>= '"+ str(min_time)+"' AND datetime<= '"+ str(max_time)+"' AND key = 72) n INNER JOIN (SELECT name, data_key, description, id FROM pub.data WHERE id = 'CM01') m ON m.key = n.key;", engine)
df['ID'] = ID
else:
df1 = df1.append(df)
df = pd.read_sql_query("SELECT key, tag name, description, datetime,
tag_value FROM (SELECT tag_value,datetime, data_key, dim_facility_key
FROM pub.values_numeric WHERE datetime>= '"+ str(min_time)+"' AND
datetime<= '"+ str(max_time)+"' AND key = 72) n INNER JOIN (SELECT name,
data_key, description, id FROM pub.data WHERE id = 'CM01') m ON m.key = n.key;", engine)
df['ID'] = ID
df1 = df1.append(df)
len(df1)
问题
我已经测试了上面的代码,并且可以正常工作,但是我不认为它足够有效/强大。
代码中的任何改进都会有所帮助。
我想要在循环中附加数据框的更pythonic /更有效的方法