【问题标题】:loop through sql query which save in the dataframe?循环通过保存在数据框中的sql查询?
【发布时间】:2020-05-30 03:42:34
【问题描述】:
  1. 用户将 sql 查询保存在 pd 中,我想执行每个 sql 查询然后放入同一个 pd 如下所示的数据框
   colunm1 = 'id1' , 'id2 '  
   column2 = 'select sum(total) from table where data_mothrn ='2020-04'' , 
             'select sum(total) from table2 where data_month ='2020-04'' , 
   column3 = 'result from column2'
             'result from column2'              
  1. 我要识字这个东西? 将每个 column2 结果按每一行放入 column3
list_para = []
def cacth_column2_sql():
    a = df_parameter['column2'].iloc[i]
    return a

def result_sql (p):
    df0 = pd.read_sql(p, conn)
    a = df0.iat[0, 0]
    list_para.append(a)


a = cacth_column2_sql() 
result_sql(a)

  1. 如何创建新列以自动保存结果?

【问题讨论】:

    标签: python read-sql


    【解决方案1】:

    您的问题需要您提供更多信息。请正确更新。

    根据我的理解:

    我创建了一个代码,它从用户(参数名称、参数数据)读取输入并将其显示在输出中。每条记录都可以通过Parameter-name访问

    import pandas as pd
    
    n_times = int(input("How many input queries you want to add"))
    
    res = []
    for i in range(0,n_times):
    
       paramname = input("Enter the id for the query ")
       paramdata = input("Enter the sql query ")
       #column3 = 'result from column2'
       result = pd.read_sql(paramdata, conn)
       #You can add code to check correct syntax here of input
       df1 = pd.DataFrame(data=[[paramname,paramdata,result]],columns= 
       ["Parameter-Name", "Parameter-Data","Result"])
       df1.index = df1.index + 1
    
    print(df1)
    

    您可以像这样通过索引访问查询

    df1.iloc[0]
    

    【讨论】:

    • 感谢@Dhruv 我编辑了这个问题。我希望查询结果附加到 column3
    • 请检查我是否进行了更改。您执行的每个查询都会将存储存储在新列结果中。希望它能解决您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2017-12-10
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多