【发布时间】:2023-03-31 03:05:02
【问题描述】:
我有一个世界各地主要机场经纬度坐标的数据库。我只需要在单独的 .csv 文件中列出的其中一部分(特别是在美国)。
这个 csv 文件有两列,我从两个列表中提取数据:始发机场代码(IATA 代码)和目的地机场代码(也是 IATA)。
我的数据库有一个 IATA 列,基本上我正在尝试查询该数据库以获取我拥有的两个列表中每个机场的相应纬度/经度坐标。
这是我的代码:
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('sqlite:///airport_coordinates.db')
# The dataframe that contains the IATA codes for the airports I need
airport_relpath = "data/processed/%s_%s_combined.csv" % (file, airline)
script_dir = os.path.dirname(os.getcwd())
temp_file = os.path.join(script_dir, airport_relpath)
fields = ["Origin_Airport_Code", "Destination_Airport_Code"]
df_airports = pd.read_csv(temp_file, usecols=fields)
# the origin/destination IATA codes for the airports I need
origin = df_airports.Origin_Airport_Code.values
dest = df_airports.Destination_Airport_Code.values
# query the database for the lat/long coords of the airports I need
sql = ('SELECT lat, long FROM airportCoords WHERE iata IN %s' %(origin))
indexcols = ['lat', 'long']
df_origin = pd.read_sql(sql, engine)
# testing the origin coordinates
print(df_origin)
这是我得到的错误:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such
table: 'JFK' 'JFK' 'JFK' ... 'MIA' 'JFK' 'MIA' [SQL: "SELECT lat, long
FROM airportCoords WHERE iata IN ['JFK' 'JFK' 'JFK' ... 'MIA' 'JFK'
'MIA']"] (Background on this error at: http://sqlalche.me/e/e3q8)
这绝对是因为我没有正确查询它(因为它认为我的查询应该是表)。
我尝试循环遍历列表以单独查询每个元素,但该列表包含超过 604,885 个元素,并且我的计算机无法提供任何输出。
【问题讨论】:
-
你也不需要自己创建SQLAlchemy引擎,你可以将
sqlite:///...URL直接传入pandas.read_sql()。 -
@MartijnPieters 你是对的,我错误地留下了从另一个函数中粘贴的内容,我在该函数中创建/输入了数据库中的数据。
-
我已经从问题中删除了 sqlite3 连接,无需为此分散注意力。
-
省点麻烦......如果你使用 sqlalchemy,你应该使用 ORM......它比手动构建 SQL 命令容易得多
标签: python database pandas sqlite sqlalchemy