在Pandas Dataframe上执行SQL并将结果存储在同一Dataframe中

时间:2019-02-08 17:40:06

标签: python pandas teradata

current dataframe

我有一个数据框,看起来像上面的图像。我想做的是遍历SQL_SCRIPT下的SQL语句,执行它们,并将结果存储在下一列中,该列称为“ RESULTS”。当我尝试执行它(不将其存储在任何地方)时,它运行良好,但是当我尝试将结果存储在新的dataframe列中时,出现以下错误:

ValueError: cannot set a row with mismatched columns

代码如下:

def run_tests(self):
    s = self.connection()
    df = self.retrieve_sql()
    df_type = df.loc[df['STEP_TYPE'] == 'T']
    df_to_list = df_type[['TABLE_NM', 'TEST_TABLE_NM', 'SQL_SCRIPT']]
    print(df_to_list)
    for sql_script in df_to_list['SQL_SCRIPT']:
        df_to_list.loc['RESULTS'] = pd.read_sql(sql_script,s)
    print(df_to_list)

我也尝试过使用会话执行代替read_sql,它也可以工作,但是我不确定如何将结果存储到该路线的数据框中:

def run_tests(self):
    s = self.connection()
    df = self.retrieve_sql()
    df_type = df.loc[df['STEP_TYPE'] == 'T']
    df_to_list = df_type[['TABLE_NM', 'TEST_TABLE_NM', 'SQL_SCRIPT']]
    print(df_to_list)
    for sql_script in df_to_list['SQL_SCRIPT']:
        s.execute(sql_script)

如果需要,这里是连接功能:

def connection(self):
    con = self.load_json_file()
    cfg_dsn = con['config']['dsn']
    cfg_usr = con['config']['username']
    cfg_pwd = con['config']['password']

    udaExec = teradata.UdaExec(appName="DataAnalysis", version="1.0", logConsole=False)
    session = udaExec.connect(method="odbc", dsn=cfg_dsn, username=cfg_usr, password=cfg_pwd)

    return session

1 个答案:

答案 0 :(得分:2)

考虑在SQL字符串列上运行Series.apply

def run_tests(self):
    s = self.connection()
    c = s.cursor()              # OPEN CURSOR
    df = self.retrieve_sql()

    df_type = df.loc[df['STEP_TYPE'] == 'T']
    df_to_list = df_type[['TABLE_NM', 'TEST_TABLE_NM', 'SQL_SCRIPT']]
    print(df_to_list)

    # NEW METHOD TO RUN QUERY
    def sql_run(x):   
        c.execute(x)
        if c.rowcount > 0:
           res = c.fetchone()[0]
        else:
           res = np.nan
        return res

    df_to_list['RESULTS'] = df_to_list['SQL_SCRIPT'].apply(sql_run)
    print(df_to_list)