简体   繁体   English

Python 循环列表到 append 表从 sqlite3

[英]Python loop list to append tables from sqlite3

Within my sqlite3 database there are hundreds of tables, but what I would like to do is create a dataframe which appends only tables from the database that match the names contained in separate list that I have made在我的 sqlite3 数据库中有数百个表,但我想做的是创建一个 dataframe,它仅附加数据库中与我制作的单独列表中包含的名称相匹配的表

The list is called 'col_list' and currently contains only 3 elements (3 names)该列表称为“col_list”,目前仅包含 3 个元素(3 个名称)

col_list = df['ref_name'].tolist()

My attempt so far has lead me to the following, which is very cumbersome.到目前为止,我的尝试导致我进行以下操作,这非常麻烦。 : :

conn = sqlite3.connect('all_data.db')
query = "SELECT * FROM " + col_list[0] + ";"
df = pd.read_sql_query(query, conn)

conn = sqlite3.connect('all_data.db')
query = "SELECT * FROM " + col_list[1] + ";"
df1 = pd.read_sql_query(query, conn)
df2 = df.append(df1)

conn = sqlite3.connect('all_data.db')
query = "SELECT * FROM " + col_list[2] + ";"
df3 = pd.read_sql_query(query, conn)
df4 = df2.append(df3)

df4 = df4.sort_values(by = 'date')
df4 = df4.reset_index(drop=True)

The number of elements in the 'col_list' can vary, which based on my current code structure means rewriting the code each time that this happens. “col_list”中的元素数量可能会有所不同,根据我当前的代码结构,这意味着每次发生这种情况时都要重写代码。 Ultimately I would like to be able to have this all work as a 'for' loop and therefore look to you guys for help.最终我希望能够让这一切作为一个“for”循环工作,因此向你们寻求帮助。

Thank you for taking the time to read this.感谢您抽出时间来阅读。

If I understood your question correctly, you want to do something like this?如果我正确理解你的问题,你想做这样的事情吗?

df_all = None
conn = sqlite3.connect('all_data.db')
for col in col_list:
    query = "SELECT * FROM " + col + ";"
    df = pd.read_sql_query(query, conn)
    if df_all is not None:
        # See also @Parfait's comment below
        # about performance cost of append()
        df_all = df_all.append(df)
    else:
        df_all = df
conn.close()
df_all = df_all.sort_values(by = 'date')
df_all = df_all.reset_index(drop=True)

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

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