【问题标题】:How to select data from SQL Server based on data available in pandas data frame?如何根据 pandas 数据框中的可用数据从 SQL Server 中选择数据?
【发布时间】:2018-01-17 17:17:39
【问题描述】:

我想查询 SQL Server 数据库的 pandas 数据框列之一中的数据列表。有什么方法可以根据我在 pandas 数据框中的数据查询 SQL Server 数据库。

select * from table_name where customerid in pd.dataframe.customerid

在 SAP 中,有一个叫做“For all entries in”的东西,SQL 可以根据数组中可用的数据查询数据库,我试图找到类似的东西。

谢谢。

【问题讨论】:

标签: python sql sql-server pandas


【解决方案1】:

如果您使用的是微型 DataFrame,那么最简单的方法是生成相应的 SQL:

In [8]: df
Out[8]:
   id  val
0   1   21
1   3  111
2   5   34
3  12   76

In [9]: q = 'select * from tab where id in ({})'.format(','.join(['?']*len(df['id'])))

In [10]: q
Out[10]: 'select * from tab where id in (?,?,?,?)'

现在您可以从 SQL Server 读取数据了:

from sqlalchemy import create_engine
conn = create_engine(...)
new = pd.read_sql(q, conn, params=tuple(df['id']))

注意:这种方法不适用于更大的 DF,因为生成的查询(和/或绑定变量列表)对于 Pandas to_sql() 函数或 SQL Server 甚至两者都可能太长。


对于更大的 DF,我建议将您的 pandas DF 写入 SQL Server 表,然后使用 SQL 子查询过滤所需的数据:

df[list_of_columns_to_save].to_sql('tmp_tab_name', conn, index=False)
q = "select * from tab where id in (select id from tmp_tab_name)"
new = pd.read_sql(q, conn, if_exists='replace')

【讨论】:

    【解决方案2】:

    这是一个非常熟悉的场景,可以使用以下代码使用非常大的 pandas 数据框查询 SQL。参数 n 需要根据您的 SQL 服务器内存进行操作。对我来说 n=25000 有效。

    n = 25000  #chunk row size
    ## Big_frame dataframe divided into smaller chunks of n into a list 
    list_df = [big_frame[i:i+n] for i in range(0,big_frame.shape[0],n)] 
    ## Create another dataframe with columns names as expected from SQL
    big_frame_2 = pd.DataFrame(columns=[<Mention all column names from SQL>]) 
    ## Print total no. of iterations
    print("Total Iterations:", len(list_df)) 
    for i in range(0,len(list_df)):
        print("Iteration :",i) 
        temp_frame = list_df[i] 
        testList = temp_frame['customer_no'] 
    ## Pass smaller chunk of data to SQL(here I am passing a list of customers)
        temp_DF = SQL_Query(tuple(testList)) 
        print(temp_DF.shape[0]) 
    ## Append all the data retrieved from SQL to big_frame_2
    big_frame_2=big_frame_2.append(temp_DF, ignore_index=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      相关资源
      最近更新 更多