使用python更改和运行SQL查询

2024-04-26 07:12:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下基于用户输入创建数据帧的代码:

import pandas as pd
  from pandas import DataFrame

 publications = 
 pd.read_csv("C:/Users/nkambhal/data/pubmed_search_results_180730.csv", sep= 
 "|")

 publications['title'] = publications['title'].fillna('')

 search_term = input('Enter the term you are looking for: ')

 publications[['title','publication_id']] 
 [publications['title'].str.contains(search_term)]
 title_mask = 
 publications.title.str.lower().str.contains(search_term.lower())
 new = publications.loc[title_mask, ['title', 'publication_ID']]

现在,我想使用新数据帧中的发布ID来运行此SQL查询:

^{pr2}$

在where语句中,我希望新数据帧中的id在那里。所以在数据框中有发布的_id(5,6,4),然后我希望将它们添加到查询中。在

如何向SQL查询添加适当的发布_id,并通过python运行它并将其保存到csv文件中?在


Tags: csv数据importidpandassearchtitlemask
1条回答
网友
1楼 · 发布于 2024-04-26 07:12:38

要将数据放入字符串,可以使用python的str.format函数。你可以多读一点here

对于您的查询字符串,其结果应该如下所示:

query_string = """
SELECT
   author_profile
   pub_lst.* 
FROM
   pub_lst
JOIN
    author_profile
        ON pub_lst.author_id = author_profile.author_id
WHERE
    pub_lst.publication_id IN {};
"""
print(query_string.format(str(tuple(new.publication_ID.values))))

至于运行查询,您将需要为任何要连接它的数据库使用python模块。例如PyMySQL,用于连接到MySQL数据库。https://pypi.org/project/PyMySQL/

不过,您可以使用peeweeSqlAlchemy之类的ORM,以便在处理SQL数据库时使您的生活更轻松一些。熊猫和炼金术结合得很好。不过,Peewee更容易开始。在

为了创建csv,您可以使用inbuildpython csv模块、pandas或{}或{}按难度升序排列。在

相关问题 更多 >