简体   繁体   中英

why doesn't pandas execute sql query?

why doesn't pandas execute sql query?

import sqlite3
import pandas as pd

# load data
df = pd.read_csv('CurriculumAuditReport.csv')

# strip whitespace from headers
df.columns = df.columns.str.strip()

con = sqlite3.connect("sans.db")

# drop data into database
df.to_sql("MyTable", con, if_exists='replace')

df = pd.read_sql_query('SELECT Count (Department) FROM MyTable WHERE `CompletedTraining` LIKE 'Incomplete' GROUP BY Department', con)
print(df)


con.close()

the query produces the result i want just fine in DB browser for SQLite

the output 
    C:\sans>C:\python34\python test2.py
  File "test2.py", line 15
    df = pd.read_sql_query('SELECT Count (Department) FROM MyTable WHERE 
`CompletedTraining` LIKE 'Incomplete' GROUP BY Department', con)


                                   ^
SyntaxError: invalid syntax

my output should have 11 rows

You have an issue with quoting - try this:

df = pd.read_sql_query("SELECT Department, count(*) as cnt FROM MyTable WHERE CompletedTraining = 'Incomplete' GROUP BY Department", con)

You can also use the following technique:

qry = """
SELECT department, count(*) as cnt
FROM MyTable
WHERE CompletedTraining = 'Incomplete'
GROUP BY department
"""
df = pd.read_sql_query(qry, con)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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