简体   繁体   English

从 python 函数中返回 DataFrame 而不是使用 Pandas 的 pd.read_sql_query 列表

[英]Return DataFrame from within python function rather than list using pandas' pd.read_sql_query

I am struggling to understand why this returns a list containing a DataFrame rather than only the DataFrame.我很难理解为什么这会返回一个包含 DataFrame 而不仅仅是 DataFrame 的列表。 Is there something wrong with the code or a way to return only the DataFrame?代码或仅返回 DataFrame 的方法有问题吗? It works as expected if not placed within a function.如果未放置在函数中,它会按预期工作。

import sqlite3
import pandas as pd

def get_tbl_info(db ='MyDatabase', table ='Measurements'):

        database = "/Users/Mary/Documents/Database/{DB}.db"..format(DB=db)

        conn = sqlite3.connect(database)

        tbl_info_command = "PRAGMA TABLE_INFO({table});".format(table=table)
        result_all = pd.read_sql_query(tbl_info_command,conn)
        print(type(result_all))
        return [result_all]



out = get_tbl_info()
print(type(out))

gives:给出:

<class 'pandas.core.frame.DataFrame'>
<class 'list'>

Because when you enclose a variable with brackets [ ] , Python understands it as "ok put this variable inside a list" .因为当您用方括号[ ]括起一个变量时,Python 会将其理解为“可以将此变量放入列表中” Just replace the return of your function with:只需将函数的return替换为:

return result_all

This should work properly, or actually your function could just return your dataframe directly这应该可以正常工作,或者实际上您的函数可以直接返回您的数据帧

return pd.read_sql_query(tbl_info_command,conn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM