Python For Data Analysis-六章三四节

《Python For Data Analysis》的第六章的第三节主要围绕requests和数据库展开。

13.1 requests模块

安装requests模块:

$sudo pip install requests

可以通过requests.get访问某个网站,返回值类似于python的文件打开函数open的返回值一样代表这正在访问的网址这对象,可以使用对象的属性和方法函数得到更多的信息,例如content属性里记录者网页的内容、json()函数返回网页里的json数据。

import requests
url = 'https://api.github.com/repos/pandas-dev/pandas/issues'
resp = requests.get(url)
print resp

13.2 数据库与dataframe

通过python访问数据库获得结果集一般是由元组组成二维列表数据rows,可以通过游标cursor获得数据库表里的字段名信息,然后用pandas的DataFrame类构造函数用rows创建dataframe数据,这是基本思想。sqlite3是轻巧的数据库,无序安装,它使用一个文件存储整个数据库,无需独立的服务器进程,操作十分方便,相比其他大型数据库来说,确实有些差距。但是在性能表现上并不逊色,麻雀虽小,五脏俱全。

import numpy as np
import sqlite3

query = """CREATE TABLE if not exists test (a VARCHAR(20), b VARCHAR(20), c REAL,d INTEGER);"""
con = sqlite3.connect('mydata.sqlite')# database
con.execute(query)# create table
con.commit()

data = [('Atlanta', 'Georgia', 1.25, 6),
        ('Tallahassee', 'Florida', 2.6, 3),
        ('Sacramento', 'California', 1.7, 5)]
sql = "INSERT INTO test VALUES(?, ?, ?, ?)"
con.executemany(sql, data)# insert datas
con.commit()

cursor = con.execute('select * from test')
rows = cursor.fetchall() # get datas
print rows, type(rows)
print cursor.description
df = pd.DataFrame(rows, columns=[x[0] for x in cursor.description])
print df
query = '''drop table if exists test;'''
con.execute(query)# drop table test
con.commit()
#print dir(cursor)

执行结果:

[(u'Atlanta', u'Georgia', 1.25, 6), (u'Tallahassee', u'Florida', 2.6, 3), (u'Sacramento', u'California', 1.7, 5)] <type 'list'>
(('a', None, None, None, None, None, None), ('b', None, None, None, None, None, None), ('c', None, None, None, None, None, None), ('d', None, None, None, None, None, None))
             a           b     c  d
0      Atlanta     Georgia  1.25  6
1  Tallahassee     Florida  2.60  3
2   Sacramento  California  1.70  5