zoukankan      html  css  js  c++  java
  • pandas Web交互和数据库交互

    一、Web交互

    很多网站都有公开的API,通过JSON或者其它格式提供数据服务。我们可以利用Python的requests库来访问这些API。Anaconda环境中默认已经安装好了requests,如果你的环境中,没有安装这个包的话,可以通过pip或者conda进行安装:

    pip install requests
    conda install requests

    下面我们以获取Github上的30条关于pandas的问题为例,介绍如何与Web API交互。

    In [113]: import requests # 导入包
    In [114]: url = 'https://api.github.com/repos/pandas-dev/pandas/issues' # 要访问的url
    In [115]: response = requests.get(url) # 访问页面,需要等待一会
    In [116]: response # 成功获取响应的数据
    Out[116]: <Response [200]>
    In [117]: data = response.json() # 解析为json格式 In [118]: data[0]['title'] # 查看第一个问题的标题 Out[118]: 'python-project-packaging-with-pandas'

    data中的每个元素都是一个包含Github问题页面上的所有数据的字典(注释除外)。

    In [119]: data[0]
    Out[119]:
    {'url': 'https://api.github.com/repos/pandas-dev/pandas/issues/24779',
     'repository_url': 'https://api.github.com/repos/pandas-dev/pandas',
     'labels_url': 'https://api.github.com/repos/pandas-dev/pandas/issues/24779/labels{/name}',
     'comments_url': 'https://api.github.com/repos/pandas-dev/pandas/issues/24779/comments',
     'events_url': 'https://api.github.com/repos/pandas-dev/pandas/issues/24779/events',
     'html_url': 'https://github.com/pandas-dev/pandas/issues/24779',
     'id': 399193081,
     'node_id': 'MDU6SXNzdWUzOTkxOTMwODE=',
     'number': 24779,
     'title': 'python-project-packaging-with-pandas',
     ......后面省略

    我们可以将data直接传给DataFrame,并提取感兴趣的字段:

    In [120]: issues = pd.DataFrame(data, columns= ['number','title','labels','state'])
    In [121]: issues
    Out[121]:
        number  ...  state
    0    24779  ...   open
    1    24778  ...   open
    2    24776  ...   open
    3    24775  ...   open
    4    24774  ...   open
    ..     ...  ...    ...
    25   24736  ...   open
    26   24735  ...   open
    27   24733  ...   open
    28   24732  ...   open
    29   24730  ...   open

    上面我们截取了'number','title','labels','state'四个字段的内容,并构造了DataFrame对象,下面就可以利用pandas对它进行各种操作了!

    二、数据库交互

    在实际使用场景中,大部分数据并不是存储在文本或者Excel文件中的,而是一些基于SQL语言的关系型数据库中,比如MySQL。

    从SQL中将数据读取为DataFrame对象是非常简单直接的,pandas提供了多个函数用于简化这个过程。

    下面以Python内置的sqlite3标准库为例,介绍一下操作过程。

    首先是生成数据库:

    In [123]: import sqlite3  # 导入这个标准内置库
    # 编写一条创建test表的sql语句
    In [124]: query = """
         ...: CREATE TABLE test
         ...: (a VARCHAR(20), b VARCHAR(20), c REAL, d integer);""" 
    In [125]: con  = sqlite3.connect('mydata.sqlite')  # 创建数据库文件,并连接
    In [126]: con.execute(query) # 执行sql语句
    Out[126]: <sqlite3.Cursor at 0x2417e5535e0>
    In [127]: con.commit # 提交事务
    Out[127]: <function Connection.commit>

    再插入几行数据:

    # 两个人和一只老鼠的信息
    In [129]: data = [('tom', 'male',1.75, 20),
         ...:         ('mary','female',1.60, 18),
         ...:         ('jerry','rat', 0.2, 60)]
         ...:
    # 再来一条空数据
    In [130]: stmt = "INSERT INTO test VALUES(?,?,?,?)"
    In [131]: con.executemany(stmt,data) # 执行多个语句
    Out[131]: <sqlite3.Cursor at 0x2417e4b9f80>
    In [132]: con.commit() # 再次提交事务

    前面都是往数据库里写入内容,下面我们来读数据:

    In [133]: cursor = con.execute('select * from test') # 执行查询语句
    In [134]: rows = cursor.fetchall() # 获取查询结果
    In [135]: rows
    Out[135]:
    [('tom', 'male', 1.75, 20),
     ('mary', 'female', 1.6, 18),
     ('jerry', 'rat', 0.2, 60)]
    In [136]: cursor.description # 看看结果中的列名,其实就是数据表的列名
    Out[136]:
    (('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))
    In [137]: pd.DataFrame(rows,columns= [x[0] for x in cursor.description])
    Out[137]:
           a     b     c   d
    0    tom    male  1.75  20
    1   mary  female  1.60  18
    2  jerry     rat  0.20  60

    上面最后生成DataFrame时,使用了一个列表推导式来构成列名序列。

    例子到这里大致就完成了,但是关于数据库的连接和查询操作实在是够繁琐的,你肯定不想每次都这么来一遍。那么怎么办呢?使用流行的Python的SQL工具包SQLAlchemy,它能简化你的数据库操作。同时,pandas提供了一个read_sql函数,允许你从通用的SQLAlchemy连接中轻松地读取数据。一个典型的操作如下:

    In [138]: import sqlalchemy as sqla 
    In [140]: db = sqla.create_engine('sqlite:///mydata.sqlite') # 创建连接
    In [141]: pd.read_sql('select * from test', db) # 查询数据并转换为pandas对象
    Out[141]:
           a       b     c   d
    0    tom    male  1.75  20
    1   mary  female  1.60  18
    2  jerry     rat  0.20  60

    在Anaconda中,已经默认安装了SQLAlchemy,可以直接使用。如果你的环境中没有SQLAlchemy,请自定安装,或者搜索教程进行学习。

  • 相关阅读:
    块设备驱动框架分析(一)
    LIN总线协议
    LCD驱动分析(三)时序分析
    str_shuffle — 随机打乱一个字符串
    str_replace — 子字符串替换
    str_repeat — 重复一个字符串
    str_pad — 使用另一个字符串填充字符串为指定长度
    str_getcsv — 解析 CSV 字符串为一个数组
    ltrim — 删除字符串开头的空白字符(或其他字符)
    lcfirst — 使一个字符串的第一个字符小写
  • 原文地址:https://www.cnblogs.com/lavender1221/p/12717754.html
Copyright © 2011-2022 走看看