import pandas as pd
import os
sale =pd.DataFrame({'year':[2010,2010,2010,2010,2011,2011,2011,2011,2012,2012,2012,2012],
'market':['东','南','西','北','东','南','西','北','东','南','西','北'],
'sale':[33912,32246,34792,31884,31651,30572,34175,30555,31619,32443,32103,31744],
'profit':[2641,2699,2574,2673,2437,2853,2877,2749,2106,3124,2593,2962]})
import sqlite3
con = sqlite3.connect(':memory:')
sale.to_sql('sale', con)
newTable = pd.read_sql_query("select year, market, sale, profit from sale", con)
newTable.head()
sqlResult = pd.read_sql_query('select * from sale', con)
sqlResult.head()
pd.read_sql_query("select DISTINCT year from sale", con)
pd.read_sql_query("select * from sale where market in ('东','西') and year=2012", con)
sql = '''select year, market, sale, profit
from sale
order by sale desc'''
pd.read_sql_query(sql, con)
one = pd.DataFrame({'x':[1,1,1,2,3,4,6],
'a':['a','a','b','c','v','e','g']})
one.to_sql('One', con, index=False)
one.T
two = pd.DataFrame({'x':[1,2,3,3,5],
'b':['x','y','z','v','w']})
two.to_sql('Two', con, index=False)
two.T
union = pd.read_sql('select * from one UNION select * from two', con)
union_all = pd.read_sql('select * from one UNION ALL select * from two', con)
union.T
union_all.T
exceptTable = pd.read_sql('select * from one EXCEPT select * from two', con)
intersectTable = pd.read_sql('select * from one INTERSECT select * from two', con)
exceptTable.T
intersectTable.T
pd.concat([one, two], axis=0, join='outer', ignore_index=True)
table1 = pd.DataFrame({'id':[1,2,3],
'a':['a','b','c']})
table1.to_sql('table1', con, index=False)
table1.head()
table2 = pd.DataFrame({'id':[4,3],
'b':['d','e']})
table2.to_sql('table2', con, index=False)
table2.head()
pd.read_sql("select * from table1, table2", con)
pd.read_sql("select * from table1 as a inner join table2 as b on a.id=b.id", con)
pd.read_sql("select * from table1 as a left join table2 as b on a.id=b.id", con)