2017-08-07 18 views
0
應用參數

我加載從SQL數據庫到Python的一些數據,但我需要申請從Python的數據幀的一些標準,加以簡化,見下面的例子:運行SQL在Python和在Python數據框中

some_sql = """ 
       select column1,columns2 
       from table 
       where a between '{}' and '{}' 
        or a between '{}' and '{}' 
        or a between '{}' and '{}' 
       """.format(date1,date2,date3,date4,date5,date6) 

date1,date2,date3,date4,date5,date6來源於Python Dataframe。我可以手動指定所有6個參數,但我確實有過,其實20 ...

 df = DataFrame({'col1':['date1','date3','date5'], 
        'col2':['date2','date4','date6']}) 

是有辦法,我能在這裏做一個循環更有效率

回答

1

設置

# Create a dummy dataframe 
df = pd.DataFrame({'col1':['date1','date3','date5'], 
        'col2':['date2','date4','date6']}) 

# Prepare the SQL (conditions will be added later) 
some_sql = """ 
select column1,columns2 
from table 
where """ 

第一種方法

conditions = [] 
for row in df.iterrows(): 
    # Ignore the index 
    data = row[1] 
    conditions.append(f"or a between '{data['col1']}' and '{data['col2']}'") 

some_sql += '\n'.join(conditions) 

通過使用iterrows(),我們可以逐行遍歷數據幀。

替代

some_sql += '\nor '.join(df.apply(lambda x: f"a between '{x['col1']}' and '{x['col2']}'", axis=1).tolist()) 

使用apply()應該更快一些iterrows():通過利用一個優勢

雖然apply()也內在地通過行循環,它這麼多 比iterrows()更有效內部優化的數量 ,比如在Cython中使用迭代器。

source

另一種選擇

​​

該功能可將數據幀到類型的字典列表,然後應用列表解析創造了條件。

結果

select column1,columns2 
from table 
where a between 'date1' and 'date2' 
or a between 'date3' and 'date4' 
or a between 'date5' and 'date6' 
+0

謝謝Kristof,對我的問題更進一步:如果我需要在SQL查詢中插入一些參數,例如,「選擇xxx然後yyy的情況」,xxx和yyy是params。我應該將sql代碼分解成條件還是使用迭代器? – Baiii

0

作爲次要的音符上面克里斯托夫的回答,我要指出,儘管分析師一個也許應該小心的東西,如SQL注入,因此內聯數據是要避免的東西。

如果可能,您應該使用佔位符定義一次查詢,然後創建一個參數列表以使用佔位符。這也節省了格式化。

所以你的情況你的查詢看起來像:

some_sql = """ 
      select column1,columns2 
      from table 
      where a between ? and ? 
       or a between ? and ? 
       or a between ? and ? 

而且我們PARAM列表生成是要看起來像:

conditions = [] 
for row in df.iterrows(): 
    # Ignore the index 
    data = row[1] 
    conditions.append(data['col1']) 
    conditions.append(data['col2']) 

然後用佔位符語法,而params列表作爲佔位符執行SQL 。

+0

謝謝克里斯 – Baiii