更新 SQLite 版本 3.5.0 后。可以使用 SQL 數學函式。如果我在 pycharm 查詢中使用它,它運行良好,但我無法在 python 代碼中執行查詢。
然后我收到以下錯誤訊息:
pandas.io.sql.DatabaseError: sql 'Select log(increase.s1) From increase' 上的執行失敗:沒有這樣的功能:日志。
我使用以下代碼執行它:
import pandas as pd
conn = sqlite3.connect('p1_database.db')
sql = "Select log(increase.s1) from increase"
pd.read_sql_query(sql, con=conn)
我的錯誤是什么?我沒有看到。
uj5u.com熱心網友回復:
如果在 sqlite3 模塊中未啟用數學函式,那么您可以將 log 函式應用于該列并回傳一個系列。
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}")
輸出:
1 0.000 0.000
2 0.693 0.301
100 4.605 2.000
uj5u.com熱心網友回復:
sqlite3標準 Python 庫中的模塊不支持數學函式。但它允許輕松創建新功能:
...
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 的日志功能實際上是一個 log10)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390810.html
