视图的Pandas read_sql()在带有空格的列中保留双引号

2024-09-28 22:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个sqlite数据库,其中有几个表的视图,其中有很多列的名称中有空格(我知道,我知道,这不是一个好的做法,但这是我无法控制的)。在

总之,我遇到的问题与使用pd.read_sql('SELECT "stupid column with space" from StupidView',con=db)时列名中的空格有关。在查询视图时,它会在列名中保留引号,而在查询表本身时则不会!表中的同一SQL返回列,而不使用引号括起来。我是不是少了点什么?你知道为什么会这样吗?在

独立工作示例:

import pandas as pd
import sqlite3
import numpy as np
pd.set_option('display.width', 1000)

# Create the database
db = sqlite3.connect("Sample Database.sqlite")
cursor = db.cursor()

# Create a table
df = pd.DataFrame({"Stupid column with space":[1,2,3,4],
                    "MrNoSpace":[1,2,3,4]})

# Push the tables to the database
df.to_sql(name="StupidTable", con=db, flavor='sqlite', if_exists='replace', index=False)

# Just in case you're running this more than once, drop the view if it exists
try: cursor.execute("DROP VIEW StupidView;")
except: pass

# Execute the sql that creates the view
cursor.execute("""
CREATE VIEW StupidView AS
SELECT StupidTable.*
FROM  StupidTable""")
db.commit()

# Execute the SQL and print the results
Test1_df = pd.read_sql('SELECT "Stupid column with space", "MrNoSpace" FROM StupidView',con=db)     # read data from the view
Test2_df = pd.read_sql('SELECT "Stupid column with space", "MrNoSpace" FROM Table1',con=db)         # same sql but on the table
Test3_df = pd.read_sql('SELECT `Stupid column with space`, `MrNoSpace` FROM StupidView',con=db)     # using ` and not "
Test4_df = pd.read_sql('SELECT  [Stupid column with space],   [MrNoSpace]  FROM StupidView',con=db) # using []

print Test1_df
print Test2_df
print Test3_df
print Test4_df

输出:

Test1_df-对视图的查询:列用双引号括起来

^{pr2}$

Test2_df-相同的查询,但在表中:现在列名中没有引号

   Stupid column with space  MrNoSpace
0                         1          1
1                         2          2
2                         3          3
3                         4          4

Test3_df-将列名包装在`(如果查询的是表而不是视图,则效果良好)

   `Stupid column with space`  `MrNoSpace`
0                           1            1
1                           2            2
2                           3            3
3                           4            4

Test4_df-完全删除列名(如果在表而不是视图上使用,效果很好)

0  1  1
1  2  2
2  3  3
3  4  4

Tags: the视图dfreaddbsqlwithcolumn
1条回答
网友
1楼 · 发布于 2024-09-28 22:22:38

这显然是Python2.7使用的sqlite版本的一个问题,它不会被正式修复(http://bugs.python.org/issue19167)。在

如果您还想使用Python2.7或更低版本,可以将C:\Python27\DLLs中的sqlite.dll替换为从这里下载的更新版本:https://www.sqlite.org/download.html。据我所知,视图现在在Python2.7中可以正常工作。在

在以下帖子的帮助下: https://stackoverflow.com/a/3341117/1754273

相关问题 更多 >