【发布时间】:2017-05-15 15:55:00
【问题描述】:
当使用 pandas read_sql 使用 SQLAlchemy 查询我的数据库时,我收到以下警告:
SAWarning:表上的列 'id' 被替换为具有相同键的 Column('id', Integer(), table=, primary_key=True, nullable=False)。考虑 select() 语句的 use_labels。 (key, getattr(existing, 'table', None), value))
对,所以我的每个 League、Season、Round、Match 和 Team 表都有一个名为 id 的列。当然。
一开始我忽略了这一点,但是当我想使用pd.drop() 删除带有id 标签/名称的列之一时,这让我感到很痛苦。甚至 pd.rename 通过其索引 (!) 引用该列重命名所有具有相同名称的列:
pandoc.rename(
columns={pandoc.columns[1]: 'match_id'},
inplace=True)
# This replaced all columns with the label `id` to `match_id`
SQLAlchemy 建议我对 select() 语句使用考虑 use_labels,虽然我设法处理常规查询,但我真的不知道在以下查询中将.label('new_column_name') 粘贴在哪里:
pandoc = pd.read_sql(
Match.query.options(
joinedload(Match.home_team),
joinedload(Match.away_team)).statement,
db.session.bind,
parse_dates=['date_time'])
一种选择是将我的表中的所有id 列更改为tablename_id,但这对于应该有一个相当简单的解决方案的问题来说似乎是一个丑陋的解决方法。
print(pandoc.head()) 的示例输出:
total_goals id round_id \
0 1.0 somestring here s12786-0
1 0.0 somestring here s12786-0
2 5.0 somestring here s12786-0
3 3.0 somestring here s12786-0
4 0.0 somestring here s12786-0
home_team_id away_team_id id id
0 667 664 667 664
1 669 691 669 691
2 672 677 672 677
3 707 686 707 686
4 699 703 699 703
注意3个id列,一个是比赛ID,另外两个是主队ID和客队ID。
【问题讨论】:
-
您能否简单地使用以下命令重命名列:df.columns = ['one', 'two', 'etc']
-
@Alan:您的意思是在所有列上设置名称(而不是替换列的名称)?因为正如我在我的 OP 中所写,不仅按名称重命名所有列(如预期的那样),甚至按索引重命名(比如 pandoc[1]/[5]/[6](这三个当前标记为
id))重命名它们! -
触发警告的原始 read_sql 查询是什么?
-
@Alan:在我的 OP 中。
-
对不起,不熟悉 SQLAlchemy,但我认为您只需要在查询中指定表即可防止冲突像那样弹出。例如使用普通的 sql 查询,您将编写“SELECT home_team FROM Team WHERE ...”,关键特性是您指定了一个表。
标签: python pandas sqlalchemy