[英]SQLite3 math functions Python
更新 SQLite 版本 3.5.0 后。 可以使用 SQL 數學函數。 如果我在 pycharm 查詢中使用它,它運行良好,但我無法在 python 代碼中執行查詢。
然后我收到以下錯誤消息:
pandas.io.sql.DatabaseError: Execution failed on sql 'Select log(increase.s1) From increase': no such function: log.
我使用以下代碼執行它:
import pandas as pd
conn = sqlite3.connect('p1_database.db')
sql = "Select log(increase.s1) from increase"
pd.read_sql_query(sql, con=conn)
我的錯誤是什么? 我沒看到。
如果在 sqlite3 模塊中未啟用數學函數,那么您可以將日志 function 應用於列並返回一個系列。
import sqlite3
import pandas as pd
import math
with sqlite3.connect(":memory:") as conn:
cur = conn.cursor()
cur.execute("create table increase(s1 integer)")
cur.execute("insert into increase (s1) values (1)")
cur.execute("insert into increase (s1) values (2)")
cur.execute("insert into increase (s1) values (100)")
df = pd.read_sql_query('SELECT * FROM increase', conn)
logseries = df['s1'].map(lambda x: math.log(x))
log10series = df['s1'].map(lambda x: math.log10(x))
for r in zip(df['s1'], logseries, log10series):
print(f"{r[0]:3d} {r[1]:.3f} {r[2]:.3f}")
Output:
1 0.000 0.000
2 0.693 0.301
100 4.605 2.000
標准 Python 庫中的sqlite3
模塊不支持數學函數。 但它允許輕松創建新功能:
...
import math
conn = sqlite3.connect('p1_database.db')
conn.create_function('log', 1, math.log10)
sql = "Select log(increase.s1) from increase"
pd.read_sql_query(sql, con=conn)
應該完成這項工作(我使用了math.log10
,因為來自 Sqlite3 的日志 function 實際上是 log10)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.