Day2 python & sql | Pandas& numpy

After finished the sql query of “python or sql” question.

step1.try to use pyodbc to query the sql server.

https://mkleehammer.github.io/pyodbc/

always remember to “import pyodbc”
连接数据库时,记得要给用户访问数据库的权限哦~(Admin登陆数据库的情况下,点击数据库-属性-文件-所有者,给予用户权限)

Connect to A Database

Pass an ODBC connection string to the connect function which will return a Connection. Once you have a connection you can ask it for a Cursor.

Select Some Data

All SQL statements are executed using Cursor.execute. If the statement returns rows, such as a select statement, you can retreive them using the Cursor fetch functions (fetchone,fetchall, fetchmany).
这里要注意,fetchone,fetchall,fetchmany切换时,需要重新执行execute语句,否则fetch的对象不对哦(因为这里其实是指针,每次操作都会移动的)。另外,fetchall比较占内存,是将所有查询结果保存在连接里面,所以尽量每次用fetchone提取自己需要的对象。——比如,用while 1这个循环来遍历。
另外,经验证,只要连接不中断,都是实时查询,也就是说,如果对数据库中数据进行了修改,重新查询的值也会修改。

Parameters

ODBC supports query parameters using a question mark as a place holder in the SQL. You provide the values for the question marks by passing them after the SQL
置后传参,即运算符后面放‘?’,参数放在最后统一传(其实也可以直接传参,即直接在运算符后面传)

Insert, Delete, Update

commit

always remember to commit the transaction.

关于Pandas 和 numpy

  • Pandas中的数据结构

Series:一维数组,与Numpy中的一维array类似。二者与Python基本的数据结构List也很相近,其区别是:List中的元素可以是不同的数据类型,而Array和Series中则只允许存储相同的数据类型,这样可以更有效的使用内存,提高运算效率。

Time- Series:以时间为索引的Series。

DataFrame:二维的表格型数据结构。很多功能与R中的data.frame类似。可以将DataFrame理解为Series的容器。以下的内容主要以DataFrame为主。

Panel :三维的数组,可以理解为DataFrame的容器。

  • 安装Pandas

通过Anaconda安装
http://pandas.pydata.org/pandas-docs/stable/install.html#installing-pandas-with-anaconda
不用这个工具安装的方法之一见
http://data-sci.info/2015/10/18/windows-%E5%AE%89%E8%A3%9Dpython-pandas%E5%A5%97%E4%BB%B6/

安装完成之后直接用IPython编辑,语法同python,网上有说IPython相较于Python自带编辑器的优点。
关于IPython常用命令参见
http://www.360doc.com/content/15/0313/11/175261_454772338.shtml

使用Anaconda Prompt进行查看和安装包操作
输入 conda list 来看一下所有安装时自带的Python扩展;输入pip install xx来安装包

  • 使用Pandas导入文本数据(txt,csv等)

import Pandas as pd
然后使用解析函数,有一堆参数可选,重点记住path(路径),names(自定义列名),index_col(索引列),header(行号,默认为0,若无header行应设置为None)。。。

《Day2 python & sql | Pandas& numpy》 pandas的解析函数.png

  • 逐块读取文本文件

很大文件时逐块读取参见(有效率对比及适用条件说明)
http://www.thebigdata.cn/JieJueFangAn/13962.html

《Day2 python & sql | Pandas& numpy》 原文件与分块读取后保存的文件对比

这里有个奇怪的现象,如果禁用行列标签则正常,如果不禁用则导出文件的第一个数据单元格有问题。

《Day2 python & sql | Pandas& numpy》 我的示例

注意,如果想要合并后按照列对齐的话,reader1的columns和reader2的要一致,这里涉及到表的连接。

  • 关于python如何切换目录
    import os
    获取当前工作目录
    os.getcwd()
    更改当前工作目录
    os.chdir(‘d:\’)

  • 关于python idle清屏
    import os
    os.system(‘cls’)

十分钟搞定pandas

参见,常见用法基本都有
http://www.cnblogs.com/chaosimple/p/4153083.html

用ipython画图的话,记得用plt.show()进行图片显示~

    原文作者:小公子
    原文地址: https://www.jianshu.com/p/d1f8c60fbfaf
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞