简体   繁体   English

python中SQLite3中的指数

[英]exponential in SQLite3 in python

I'm wrting a python code that creates a SQLite database and does some calculations for massive tables.我正在编写一个 python 代码,它创建一个 SQLite 数据库并对大量表进行一些计算。 To begin with, reason i'm doing it in SQLite through python is memory, my data is huge that will break into a memory error if run in, say, pandas.首先,我通过 python 在 SQLite 中执行此操作的原因是内存,我的数据很大,如果在 Pandas 中运行,则会出现内存错误。 and if chuncked it'll take ages, generally because pandas is slow with merges and groupes, etc.如果压缩它会花费很长时间,通常是因为熊猫在合并和分组等方面很慢。

So my issue now is at some point, i want to calculate exponential of one column in a table (sample code below) but it seems that SQLite doesn't have an EXP function.所以我现在的问题是在某个时候,我想计算表中一列的指数(下面的示例代码),但似乎 SQLite 没有 EXP 函数。

I can write data to a dataframe and then use numpy to calculate the EXP but that then beats the whole point that pushed my twoards DBs and not have the additional time of reading/writing back and forth between the DB and python.我可以将数据写入数据帧,然后使用 numpy 来计算 EXP,但这超过了推动我的 twoards DB 的重点,并且没有额外的时间在 DB 和 python 之间来回读/写。

so my question is this: is there a way around this to calculate the exponential within the database?所以我的问题是:有没有办法解决这个问题来计算数据库中的指数? i've read that i can create the function within sqlite3 in python, but i have no idea how.我读过我可以在 python 中的 sqlite3 中创建函数,但我不知道如何。 If you know how or can direct me to where i can find relavent info then i would be thankful, thanks.如果您知道如何或可以指导我到哪里可以找到相关信息,那么我将不胜感激,谢谢。

Sample of my code where i'm trying to do the calculation, note here i'm just providing a sample where the table is coming directly from a csv, but in my process it's actually created within the DB after lots of megres and group bys:我试图进行计算的代码示例,请注意这里我只是提供一个示例,其中表直接来自 csv,但在我的过程中,它实际上是在经过大量 megres 和 group bys 之后在数据库中创建的:

import sqlite3

#set path and files names
folderPath = 'C:\\SCP\\'
inputDemandFile = 'demandFile.csv'

#set connection to database
conn = sqlite3.connect(folderPath + dataBaseName)
cur = conn.cursor()

#read demand file into db
inputDemand = pd.read_csv(folderPath + inputDemandFile)
inputDemand.to_sql('inputDemand', conn, if_exists='replace', index=False)

#create new table and calculate EXP
cur.execute('CREATE TABLE demand_exp AS SELECT from_zone_id, to_zone_id, EXP(demand) AS EXP_Demand FROM inputDemand;')

i've read that i can create the function within sqlite3 in python, but i have no idea how.我读过我可以在 python 中的 sqlite3 中创建函数,但我不知道如何。

That's conn.create_function()那是conn.create_function()

https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function

>>> import math
>>> conn.create_function('EXP', 1, math.exp)
>>> cur.execute('select EXP(1)')
>>> cur.fetchone()
(2.718281828459045,)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM