1. 运算优先级括号、指数、乘、除、加、减
2如果你使用了非 ASCII 字符而且碰到了编码错误,记得在最顶端加一行 # -- coding: utf-8 --
3. Python格式化字符使用更多的格式化字符。例如 %r 就是是非常有用的一个,它的含义是“不管什么都打印出来”。%s -- string
%% 百分号标记 #就是输出一个%%c 字符及其ASCII码%s 字符串%d 有符号整数(十进制)%u 无符号整数(十进制)%o 无符号整数(八进制)%x 无符号整数(十六进制)%X 无符号整数(十六进制大写字符)%e 浮点数字(科学计数法)%E 浮点数字(科学计数法,用E代替e)%f 浮点数字(用小数点符号)%g 浮点数字(根据值的大小采用%e或%f)%G 浮点数字(类似于%g)%p 指针(用十六进制打印值的内存地址)%n 存储输出字符的数量放进参数列表的下一个变量中
%c 转换成字符(ASCII 码值,或者长度为一的字符串)%r 优先用repr()函数进行字符串转换(Python2.0新增)%s 优先用str()函数进行字符串转换%d / %i 转成有符号十进制数%u 转成无符号十进制数%o 转成无符号八进制数%x / %X (Unsigned)转成无符号十六进制数(x / X 代表转换后的十六进制字符的大小写)%e / %E 转成科学计数法(e / E控制输出e / E)%f / %F 转成浮点数(小数部分自然截断)%g / %G : %e和%f / %E和%F 的简写%% 输出%
辅助符号 说明
* 定义宽度或者小数点精度- 用做左对齐+ 在正数前面显示加号(+)<sp> 在正数前面显示空格# 在八进制数前面显示零(0),在十六进制前面显示“0x”或者“0X”(取决于用的是“x”还是“X”)0 显示的数字前面填充“0”而不是默认的空格m.n m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)
4.binary = "B1"print "%r" %binaryprint "%s" %binary结果:'binary'binary
5.end1 = "C"end2 = "h"print end1, end2结果:C h# 逗号 ( , ) 输出后为空格 ( )
6.print "word %r" % "didn't" #对象中有单引号 ( ' ),输出结果含有“ ”print "word %r" % "did not"
print "word %s" % "didn't"print "word %s" % "did not"
结果:word "didn't"word 'did not'word didn'tword did not
7.print """"""(等效于print '''''')结果:空行
8.months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"print "%r" %monthsprint months结果:'Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'JanFebMarAprMayJunJulAug
9.转义符功能\\ Backslash ()反斜杠\' Single quote(‘) 单引号\" Double quote(”) 双引号\a ASCII Bell(BEL) 响铃符\b ASCII Backspace (BS) 退格符\f ASCII Formfeed (FF) 进纸符\n ASCII Linefeed (LF) 换行符\N{name} Unicode 数据库中的字符名,其中 name 就是它的名字(Unicode only)\r ASCII Carriage Return (CR)回车符\t ASCII HorizontalTab (TAB) 水平制表符\uxxxx 值为 16 位十六进制值xxxx 的字符(Unicode only)\Uxxxxxxxx 值为 32 位十六进制值xxxx 的字符(Unicode 转义符功能only)\v ASCII Vertical Tab (VT) 垂直制表符\ooo 值为八进制值 ooo 的字符\xhh 值为十六进制数 hh 的字符
10.记住这条:``%r`` 用作 debug,``%s`` 用作显示。
11. input( ) 和 raw_input( )input() 函数会把你输入的东西当做 Python 代码进行处理,这么做会有安全问题,你应该避开这个函数。x = raw_input() 默认输入格式为string,如需整数,则需要用int转化为数字y = int (x)
12.y = raw_input("Name? ")“Name?” 提示用户,然后将用户输入的结果赋值给变量 y。
13.python中的help和pydoc都是干什么的,有何不同?pydoc 是把 help 的内容转成 HTML 输出。两者内容都来自 python 模块中的 docstring
Window,那就试一下 python -m pydoc raw_input 。LINUX/ MAX : 在命令行输入 pydoc raw_input
14. 提示别人age = raw_input("How old are you? ")print "My old is %r." %age结果:How old are you?输入20My old is '20'.
15.raw_input() 和 import argv结合程序:from sys import argv
script, s1, s2 = argvinput_1 = raw_input("Your " + s1 + " is:")input_2 = raw_input("Your " + s2 + " is:")
print "Your input %s is: %s" % (s1, input_1)print "Your input %s is: %s" % (s2, input_2)
运行:python try.py a bYour a is: 输入 beyondYour b is: 输入 yourself输出:Your input a is beyond.Your input b is yourself.
16.argv 和 raw_input() 有什么不同?不同点在于用户输入的时机。如果参数是在用户执行命令时就要输入,那就是 argv,如果是在脚本运行过程中需要用户输入,那就使用 raw_input()。
17.print """%r is %r""" % (x, y)
18. from sys import argv 是什么意思?
现在能告诉你的是, sys 是一个代码库,这句话的意思是从库里取出 argv 这个功能来,供我使用。
19. 关于 .read() 和 .readline()
程序:txt = open(filename)print txt.readline()print txt.read()
文件 (ex15_sample.txt) 的内容:This is stuff I typed into a file.It is really cool stuff.Lots and lots of fun to have in here.

结果:PS C:\Users\310118430\onedrive\python\program> python ex15.py ex15_sample.txtThis is stuff I typed into a file.
It is really cool stuff.Lots and lots of fun to have in here.
20.
close – 关闭文件。跟你编辑器的 文件->保存.. 一个意思。• read – 读取文件内容。你可以把结果赋给一个变量。• readline – 读取文本文件中的一行。• truncate – 清空文件,请小心使用该命令。• write(stuff) – 将stuff 写入文件。
21.target = open(filename,'w')如果用了 'w' 参数, truncate() 是必须的吗?貌似没看出来什么影响。都会自动抹除
中 'w' 是什么意思?它只是一个特殊字符串,用来表示文件的访问模式。如果你用了 'w' 那么你的文件就是写入(write)模式。除了 'w' 以外,我们还有 'r' 表示读取(read), 'a' 表示追加(append)。
还有哪些修饰符可以用来控制文件访问?最重要的是 + 修饰符,写法就是 'w+', 'r+', 'a+' ——这样的话文件将以同时读写的方式打开,而对于文件位置的使用也有些不同。PS:当使用open(filename, 'a')形式改写,不会自动擦写,需要使用truncate()把原来的内容擦除。否则,就会在原来内容基础上 续写。
如果只写 open(filename) 那就使用 'r' 模式打开的吗?是的,这是 open() 函数的默认工作方式。
22. len( )它会以数字的形式返回你传递的字符串的长度。试着玩玩吧。
23.创建函数 defdef print_two (*args):arg1, arg2 = argsprint "arg1: %r, arg2: %r" % (arg1, arg2)def print_two_again(arg1, arg2):print "arg1: %r, arg2: %r" %(arg1, arg2)
24.*args 的 * 是什么意思?它的功能是告诉 python 让它把函数的所有参数都接受进来,然后放到名字叫 args 的列表中去。和你一直在用的 argv 差不多,只不过前者是用在函数上面。没什么特殊情况,我们一般不会经常用到这个东西。
def print_two (*args):arg1, arg2 = argsprint "arg1: %r, arg2: %r" % (arg1, arg2)
print_two("Zed", "Shaw")
25.函数的形式def func(a, b):print ...
切记:勿忘冒号
26.Python File seek() 方法 fileObject.seek(offset[, whence])
参数
  • offset-- 开始的偏移量,也就是代表需要移动偏移的字节数
  • whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
返回值该函数没有返回值。
实例以下实例演示了 readline() 方法的使用:文件 runoob.txt 的内容如下:1:www.runoob.com2:www.runoob.com3:www.runoob.com4:www.runoob.com5:www.runoob.com循环读取文件的内容:#!/usr/bin/python# -*- coding: UTF-8 -*-# 打开文件fo= open("runoob.txt","rw+")print"文件名为: ", fo.nameline= fo.readline()print"读取的数据为: %s"%(line)# 重新设置文件读取指针到开头fo.seek(0,0)line= fo.readline()print"读取的数据为: %s"%(line)# 关闭文件fo.close()以上实例输出结果为:文件名为: runoob.txt读取的数据为:1:www.runoob.com读取的数据为:1:www.runoob.com
27. 逗号 , 与空行def print_a_line(line_count, f):print line_count, f.readline(),结果:1 A MIAO JIAO2 B ZHAO RUBING3 C MIAO XIZHAO
def print_a_line(line_count, f):print line_count, f.readline()结果:1 A MIAO JIAO
2 B ZHAO RUBING
3 C MIAO XIZHAO
二者差距只是在f.readline() 后面是否有“ , ”。如果有逗号,则可以少打印一个空行。
解释:问什么文件里会有间隔空行?readline() 函数返回的内容中包含文件本来就有的 \n,而 print 在打印时又会添加一个\n,这样一来就会多出一个空行了。解决方法是在 print 语句结尾加一个逗号 ,,这样 print 就不会把它自己的 \n 打印出来了。
28.
readline() 是怎么知道每一行在哪里的?readline() 里边的代码会扫描文件的每一个字节,直到找到一个 \n 为止,然后它停止读取文件,并且返回此前的文件内容。文件 f 会记录每次调用 readline() 后的读取位置,这样它就可以在下次被调用时读取接下来的一行了。
29.在.py文件中仅定义了函数 def调用方法:cmd -- 运行 python --import ex25运行words = ex25.sort_words
说明:把 ex25.py 当做了一个“模组(module)”来使用
30.string.split(' ')def break_words(stuff):"""This function will break up words for us."""words = stuff.split(' ')return words说明:将字符串中的空格去除,字符用 ’' 标注出来结果:>>> words['All', 'goo', 'things', 'come', 'to', 'those', 'who', 'wait.']
31. 字母表排序def sort_words(words):"""Sorts the words."""return sorted(words)结果:>>> sorted_words['All', 'come', 'goo', 'things', 'those', 'to', 'wait.', 'who']
但如果对于sentence排序,则被认为对每个字符排序>>> sorted_words = ex25.sort_words(sentence)>>> sorted_words[' ', ' ', ' ', ' ', ' ', ' ', ' ', '.', 'A', 'a', 'c', 'e', 'e', 'g', 'g', 'h','h', 'h', 'i', 'i', 'l', 'l', 'm', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 's', 's','t', 't', 't', 't', 'w', 'w']
32. .pop 首字符串、尾字符串word = words.pop(0) 首字符串word = words.pop(-1) 尾字符串
def print_first_word(words):"""Prints the first word after popping it off."""word = words.pop(0)print word
注意:words首字符串打印出来之后,words被改变,原来的首字符串被拿走了
问题:函数里的代码不是只在函数里有效吗?为什么 words.pop(0) 这个函数会改变 words 的内容?答案:这个问题有点复杂,不过在这里 words 是一个列表,你可以对它进行操作,操作结果也可以被保存下来。这和你操作文件时文件的 f.readline() 工作原理差不多。
如何避免??-- 做一个封装即可:def print_first_and_last(sentence):words = break_words(sentence)print_first_word(words)说明:每次运行输入sentence,建一个临时变量words,在print_first_word,原sentence未受影响
33. if condition :if cars > people:print "We should take the cars."elif cars < people:print "We should not take the cars."else:print "We can't decide."
34. for i in xxx:数组element = []for 条件 range(0,6)elements = [] #similar as array in C/C++# then use the range function to do 0 to 5 countsfor iinrange(0, 6): print "Adding %d to the list." % i# append is a function that lists understandelements.append(i)print elements
结果:[0, 1, 2, 3, 4, 5]
说明:为什么 for i in range(1, 3): 只循环 2 次而非 3 次?range() 函数会从第一个数到最后一个,但不包含最后一个数字。所以它在 2 的时候就停止了,而不会数到 3。这种含首不含尾的方式是循环中及其常见的一种用法。elements.append() 是什么功能?它的功能是在列表的尾部追加元素。打开 Python 命令行,创建几个列表试验一下。以后每次碰到自己不明白的东西,你都可以在 Python 的交互式命令行中实验一下
35.
next = raw_input("> ")if "flee"in next: #如果raw_input输入的内容中含有flee字符....
36while True: #创建一个无限循环。
37exit(0) 有什么功能?在很多类型的操作系统里,``exit(0)`` 可以中断某个程序,而其中的数字参数则用来表示程序是否是碰到错误而中断。 exit(1) 表示发生了错误,而 exit(0) 则表示程序是正常退出的。这和我们学的布尔逻辑 0==False 正好相反,不过你可以用不一样的数字表示不同的错误结果。比如你可以用 exit(100) 来表示另一种和 exit(2) 或 exit(1) 不同的错误。
38. 关于 双引号“ " 和 单引号 ' '
错误:“I am 6'2" tall." 其中2”会产生歧义,无法判断2之后的“ 是否是待输出内容。
正确做法1:加入 \""I am 6'2\" tall." # 将字符串中的双引号转义
' ' 同样适用'I am 6\'2" tall.' # 将字符串种的单引号转义,从而防止它被识别为字符串的结尾。
正确做法2:"""print """I am 6'2" tall. #输出的内容"""

39.类似于数组的用法,地址为CA,值为San Francisco
#create a basic set of states and some cities in themcities = {'CA': 'San Francisco', #some like array, address is CA, and value is "San Franc.."'MI': 'Detroit','FL': 'Jacksonville'}
40for 循环
foraddress,value inarray.items():......
states = {'Oregon': 'OR','Florida': 'FL','California': 'CA','New York': 'NY','Michigan': 'MI'}for state, abbrev in states.items():#state和abbrev都是临时变量,分别被赋予states的地址、值print "%s is abbreviated %s" %(state, abbrev)
41数组中的查找函数
state = states.get('California', None)
if not state:print "Sorry, no Texas."else:print "States.get() result is %s" %(state)
结果:States.get() result is CA
42a=5isinstance(a, int)//isinstance函数,检查一个对象是否是某个特定类型的实例out: True
43元组:代码如下:tup1 = ('physics', 'chemistry', 1997, 2000);tup2 = (1, 2, 3, 4, 5 );tup3 = "a", "b", "c", "d";
创建空元组复制代码代码如下:tup1 = ();
元组中只包含一个元素时,需要在元素后面添加逗号来消除歧义复制代码代码如下:tup1 = (50,);
44.可变对象:列表 [ ]、字典、Numpy数组不可变对象:字符串、元组( )
例:a_list = ['foo', 2, [4,5]]a_list[0] = 'a' //a_list变为['a', 2, [4,5]]
b_tuple = ('foo', 2, [4,5])b_tuple[0] = 'a' //error,元组不能被改变
45. 集合运算

46.字典{'key1': value1, 'key2': value2, ... }元组(value1, value2, ...)列表[value1, value2, value3, ... ]
47.[expr for val in collection if condition]
48 lambda例:ints=[4,0,1,5,6]apply_to_list(ints, lambda x : x*2)# 相当于return x*2,只不过不用define函数,直接返回值
例2:def add_numbers(x, y):return x+y
add_five = lambda y: add_numbers(5, y)
等效于
from functools import partialadd_five = partical(add_numbers, 5)
49.python的数据结构与C++不一样。C++中,数组、vector等,每一层元素,性质、名称在刚开始都列的很清楚。而Python中,多维数据结构的话,常常在定义的时候,说的不清楚。
例: #python程序
def get_counts(sequence):counts={}for x in sequence:if x in counts:counts[x]+=1else:counts[x]=1return counts
time_zones=['America/New_York', 'America/Denver', 'America/New_York', 'America/Sao_Paulo', 'America/New_York', 'America/New_York', 'Europe/Warsaw']
dict1=get_counts(time_zones)print dict1print dict1['America/New_York']
print len(time_zones)
结果:{'Europe/Warsaw': 1, 'America/Denver': 1, 'America/Sao_Paulo': 1, 'America/New_York': 4}47
分析:定义函数function get_counts( sequence), 包含变量 列表list sequence在函数function内部定义临时变量:新建 字典 counts列表中的元素 x,并将x赋值给counts作为字典的key在函数的结尾部分,return语句看出函数的返回值类型为 字典,值为counts
在调用的过程中,定义一个变量 字典 dict = get_counts (time_zones)直接打印,发现程序自动做了遍历,将所有字典的key都搜索了一遍。
50.用pylab画图
输入 from pylab import *
51.Python split()方法描述Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串语法split()方法语法:str.split(str="", num=string.count(str)).参数
  • str -- 分隔符,默认为空格。
  • num -- 分割次数。
返回值返回分割后的字符串列表。实例以下实例展示了split()函数的使用方法:#!/usr/bin/pythonstr = "Line1-abcdef \nLine2-abc \nLine4-abcd";print str.split( );print str.split(' ', 1 );以上实例输出结果如下:['Line1-abcdef', 'Line2-abc', 'Line4-abcd']['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
52. Series
Series 是一个 一维数组对象 ,类似于 NumPy 的一维 array。它除了包含一组数据还包含一组索引,所以可以把它理解为一组带索引的数组。将 Python 数组转换成 Series 对象:

将 Python 字典转换成 Series 对象:

当没有显示指定索引的时候,Series 自动以 0 开始,步长为 1 为数据创建索引。你也可以通过 index 参数显示指定索引:对于 Series 对象里的单个数据来说,和普通数组一样,根据索引获取对应的数据或重新赋值;不过你还可以传入一个索引的数组来获取数据或未数据重新赋值:
例:from pandas import Series, DataFrameimport pandas as pd
dic = {'a':2,'b':5, 'c':7, 'd':4}obj3 = Series(dic)

想要单独获取 Series 对象的索引或者数组内容的时候,可以使用 index 和 values 属性,例如:对 Series 对象的运算(索引不变):
53. DataFrameDataFrame 是一个 表格型 的数据结构。它提供 有序的列 和 不同类型的列值 。例如将一个由 NumPy 数组组成的字典转换成 DataFrame 对象:
例:from pandas import Series, DataFrameimport pandas as pd
data = {'name':['Carl', 'Peter', 'Lucy', 'Job'], 'age':[30,34,20,35], 'gender':['m','m','f','m']}frame = DataFrame(data)
执行:

DataFrame 默认根据列名首字母顺序进行排序,想要指定列的顺序?传入一个列名的字典即可:如果传入的列名找不到,它不会报错,而是产生一列 NA 值:

DataFrame 不仅可以以字典索引的方式获取数据,还可以以属性的方法获取,例如:

修改列的值:

删除某一列:

改变Lucy 的重量为50kg:程序:from pandas import Series, DataFrameimport pandas as pd
data = {'name':['Carl', 'Peter', 'Lucy', 'Job'], 'age':[30,34,20,35], 'gender':['m','m','f','m']}frame = DataFrame(data)
frame2 = DataFrame(data, columns = ['name', 'weight', 'gender', 'age'])
temp_weight = frame2['weight']temp_weight[frame2['name']=='Lucy'] = 50
执行:
分析:引用:赋值号“=”是引用在Python中,赋值一个复杂数据结构 D(比如DataFrame)之后,在命名一个分支数据结构 L 例如列表,并将D的数据用 等号 = 复制给L。对于L中的数据做修改,D中的数据也同时被改掉了。这一点与C++完全不同。
浅层拷贝:object_new = copy.copy(object_old)赋值一个多层结构之后,新建元素,实现了拷贝,但是对于原有元素使用.append()等函数进行拓展、修改,则object_new 和 object_old 都进行了变化。
深层拷贝:object_new = copy.deepcopy(object_old)object_new和object_old完全割裂开来,对于二者之一进行改变,另一个对象不会变。具体即使见54. python 对象拷贝
54.python 对象拷贝 小例奉上: 可以看出,赋值号“=”是引用,即a 和 b 是指向一个对象。 如何实现对象的拷贝呢,python 有 copy模块。用法:import copy 对象2 = copy.copy(对象1)例子:问题: 可以看出:copy 可以实现浅层拷贝,可以通过copy.deepcoppy()来实现深层拷贝。例如上例:判断是否是一个对象: is "b = a"是引用 指向的一个对象,所以a is b返回 True "c = copy.copy(a)"c是a的拷贝,不是指向一个对象,返回False判断是否值相同: ==
55.DataFrame.dropna()假如数据量比较大或者有冗余,我们可以删掉有缺失值的数据,你可以选择删除行或者删除列,用的都是DataFrame.dropna(),当然Series也有dropna方法,用法相同。
  1. 引入相关模块
  1. 创建一个带有缺失值的数据框:
查看一下数据内容:
  1. 通常情况下,我们选择删除行,使用参数axis=0,这是最常用的方法
删除后的结果为:
  1. 还有可能的是,我们选择删除列,这种情况不多,因为通常我们选择用列表示一个变量或者指标,我们通常不会因为有几个缺失值就删除一个变量
输出结果为:
官方解释pandas.DataFrame.dropnaDataFrame.dropna(axis=0,how='any',thresh=None,subset=None,inplace=False)[source]Return object with labels on given axis omitted where alternately any or all of the data are missing

56. fillna、布尔数组、value_counts()fillna函数可以替换缺失值(NA),布尔型数组可以替换元素,.value_counts()对于series类型数据,进行频次排序
例:clean_tz = frame['tz'].fillna('Missing')clean_tz[clean_tz == ' '] = 'Unknown'tz_counts = clean_tz.value_counts()
官方data:pandas.Series.value_countsSeries.value_counts(normalize=False,sort=True,ascending=False,bins=None,dropna=True)[source]Returns object containing counts of unique values.The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default.
57. DataFrame, .groupby(), .size(), .unstack(),
个人理解:
DataFrame有点类似于excel表格,新建方式有以下两大类:一、将dict直接转化为DataFramedf = pd.DataFrame({'key1':['a','a','b','b','a'], 'key2':['one','two','one','two','one'],'data1':np.random.randn(5),'data2':np.random.randn(5)})
d1={'key1':['a','a','b','b','a'], 'key2':['one','two','one','two','one'],'data1':np.random.randn(5),'data2':np.random.randn(5)}
DF = pandas.DataFrame(d1.items(), columns = ['Y1', 'Y2'])
DF2 = pandas.DataFrame(list_1)
二、指定表格中的数值,然后指定行的名称和列的名称简单表格:people = pd.DataFrame(np.random.randn(5,4), columns = ['a','b','c','d'], index=['Joe','Steve','Wes','Jim','Travis']) #其中(5, 4)是数据的行数和列数
复杂表格:columns2 = pd.MultiIndex.from_arrays([['US', 'US', 'US', 'JP', 'JP'],[1, 3, 5, 1, 3]], names=['cty', 'tenor'])hier_df = pd.DataFrame(np.random.randn(4,5),columns=columns2)
hier_df输出cty US JP tenor 1 3 5 1 30 0.718198 0.613803 0.333938 1.316058 -1.4435131 0.267548 -0.900000 -2.002760 0.065267 -0.9084162 -0.065379 1.877671 -1.590868 -1.439815 -1.6866763 -1.186946 0.809720 0.095537 0.810359 1.360787
.groupby()是对DataFrame的分析手段,本身无法打印出来,需要转化为groupby格式,然后进行运算:mean(), sum() 等
DataFrame.groupby().mean()的数据类型为 Series
例:means = df['data1'].groupby([df['key1'], df['key2']]).mean()#data1是待运算的数据,key1和key2是分类的方式,.mean()是求值运算法则
.size()DataFrame['data1'].groupby(['key1','key2',...]).size() 类似于Series.value_counts()用于记录重复频次
>>> df.groupby(['key1', 'key2']).size()key1 key2a one 2 two 1b one 1 two 1dtype: int64

.unstack()DataFrame['data1'].groupby(['key1','key2',...]).mean().unstack()
DataFrame.mean().unstack()数据类型为DataFrame将groupby运算的内容从纯列格式(只有表头和数据),重新排列为行列式(拥有行头、列头和数据)-->将.mean()的Series格式,转化为DataFrame()格式>>> means = df['data1'].groupby([df['key1'], df['key2']]).mean()>>> meanskey1 key2a one -0.714084 two -2.120793b one 0.642216 two 0.975133dtype: float64
>>> means.unstack()key2 one twokey1 a -0.714084 -2.120793b 0.642216 0.975133



例:operating_system = np.where(cframe['a'].str.contains('Windows'),'Windows','Not Windows')#operating_system类型是numpy.ndarrayby_tz_os = cframe.groupby(['tz',operating_system])#by_tz_os类型是pandas.core.groupby.DataFrameGroupBy
数据聚合与分组运算——GroupBy技术(1),有需要的朋友可以参考下。


pandas提供了一个灵活高效的groupby功能,它使你能以一种自然的方式对数据集进行切片、切块、摘要等操作。

  • 根据一个或多个键(可以是函数、数组或DataFrame列名)拆分pandas对象。
  • 计算分组摘要统计,如计数、平均值、标准差,或用户自定义函数。
  • 对DataFrame的列应用各种各样的函数。
  • 应用组内转换或其他运算,如规格化、线性回归、排名或选取子集等。
  • 计算透视表或交叉表。
  • 执行分位数分析以及其他分组分析。


1、分组键可以有多种形式,且类型不必相同

  • 列表或数组,其长度与待分组的轴一样。
  • 表示DataFrame某个列名的值。
  • 字典或Series,给出待分组轴上的值与分组名之间的对应关系。
  • 函数,用于处理轴索引或索引中的各个标签。

注意:
后三种都只是快捷方式而已,其最终目的仍然是产生一组用于拆分对象的值。

2、首先来看看下面这个非常简单的表格型数据集(以DataFrame的形式):

>>> import pandas as pd>>> df = pd.DataFrame({'key1':['a', 'a', 'b', 'b', 'a'],... 'key2':['one', 'two', 'one', 'two', 'one'],... 'data1':np.random.randn(5),... 'data2':np.random.randn(5)})>>> df data1 data2 key1 key20 -0.410673 0.519378 a one1 -2.120793 0.199074 a two2 0.642216 -0.143671 b one3 0.975133 -0.592994 b two4 -1.017495 -0.530459 a one假设你想要按key1进行分组,并计算data1列的平均值,我们可以访问data1,并根据key1调用groupby:
>>> grouped = df['data1'].groupby(df['key1'])>>> grouped<pandas.core.groupby.SeriesGroupBy object at 0x04120D70>变量grouped是一个GroupBy对象,它实际上还没有进行任何计算,只是含有一些有关分组键df['key1']的中间数据而已,然后我们可以调用GroupBy的mean方法来计算分组平均值:

>>> grouped.mean()key1a -1.182987b 0.808674dtype: float64说明:数据(Series)根据分组键进行了聚合,产生了一个新的Series,其索引为key1列中的唯一值。之所以结果中索引的名称为key1,是因为原始DataFrame的列df['key1']就叫这个名字。

3、如果我们一次传入多个数组,就会得到不同的结果:
>>> means = df['data1'].groupby([df['key1'], df['key2']]).mean()>>> meanskey1 key2a one -0.714084 two -2.120793b one 0.642216 two 0.975133dtype: float64

通过两个键对数据进行了分组,得到的Series具有一个层次化索引(由唯一的键对组成):

>>> means.unstack()key2 one twokey1 a -0.714084 -2.120793b 0.642216 0.975133在上面这些示例中,分组键均为Series。实际上,分组键可以是任何长度适当的数组:

>>> states = np.array(['Ohio', 'California', 'California', 'Ohio', 'Ohio'])>>> years = np.array([2005, 2005, 2006, 2005, 2006])>>> df['data1'].groupby([states, years]).mean()California 2005 -2.120793 2006 0.642216Ohio 2005 0.282230 2006 -1.017495dtype: float64


4、此外,你还可以将列名(可以是字符串、数字或其他Python对象)用作分组将:

>>> df.groupby('key1').mean() data1 data2key1 a -1.182987 0.062665b 0.808674 -0.368333>>> df.groupby(['key1', 'key2']).mean() data1 data2key1 key2 a one -0.714084 -0.005540 two -2.120793 0.199074b one 0.642216 -0.143671 two 0.975133 -0.592994说明:在执行df.groupby('key1').mean()时,结果中没有key2列。这是因为df['key2']不是数值数据,所以被从结果中排除了。默认情况下,所有数值列都会被聚合,虽然有时可能会被过滤为一个子集。
无论你准备拿groupby做什么,都有可能会用到GroupBy的size方法,它可以返回一个含有分组大小的Series:

>>> df.groupby(['key1', 'key2']).size()key1 key2a one 2 two 1b one 1 two 1dtype: int64注意:分组键中的任何缺失值都会被排除在结果之外。

5、对分组进行迭代
GroupBy对象支持迭代,可以产生一组二元元组(由分组名和数据块组成)。看看下面这个简单的数据集:


>>> for name, group in df.groupby('key1'):#name指的是groupby()中的元素'key1',group指的是数据集合... print(name)... print(group)... a data1 data2 key1 key20 -0.410673 0.519378 a one1 -2.120793 0.199074 a two4 -1.017495 -0.530459 a oneb data1 data2 key1 key22 0.642216 -0.143671 b one3 0.975133 -0.592994 b two
例:for name, in df.groupby('key1'):#name指的是groupby()中的元素'key1',没有group... print(name)
输出:('a', data1 data2 key1 key20 0.216977 -1.886116 a one1 -0.551853 1.053309 a two4 0.841869 1.509615 a one)('b', data1 data2 key1 key22 -0.563219 -0.001156 b one3 0.223015 0.986681 b two)
对于多重键的情况,元组的第一个元素将会是由键值组成的元组:

>>> for (k1, k2), group in df.groupby(['key1', 'key2']):#(k1, k2)指的是groupby()中的元素['key1','key2']... print k1, k2... print group... a one data1 data2 key1 key20 -0.410673 0.519378 a one4 -1.017495 -0.530459 a onea two data1 data2 key1 key21 -2.120793 0.199074 a twob one data1 data2 key1 key22 0.642216 -0.143671 b oneb two data1 data2 key1 key23 0.975133 -0.592994 b two当然,你可以对这些数据片段做任何操作。有一个你可能会觉得有用的运算:将这些数据片段做成一个字典:
>>> pieces = dict(list(df.groupby('key1')))>>> pieces['b'] data1 data2 key1 key22 0.642216 -0.143671 b one3 0.975133 -0.592994 b two>>> df.groupby('key1')<pandas.core.groupby.DataFrameGroupBy object at 0x0413AE30>>>> list(df.groupby('key1'))[('a', data1 data2 key1 key20 -0.410673 0.519378 a one1 -2.120793 0.199074 a two4 -1.017495 -0.530459 a one), ('b', data1 data2 key1 key22 0.642216 -0.143671 b one3 0.975133 -0.592994 b two)]groupby默认是在axis=0上进行分组的,通过设置也可以在其他任何轴上进行分组。那上面例子中的df来说,我们可以根据dtype对列进行分组:
>>> df.dtypesdata1 float64data2 float64key1 objectkey2 objectdtype: object>>> grouped = df.groupby(df.dtypes, axis=1)>>> dict(list(grouped)){dtype('O'): key1 key20 a one1 a two2 b one3 b two4 a one, dtype('float64'): data1 data20 -0.410673 0.5193781 -2.120793 0.1990742 0.642216 -0.1436713 0.975133 -0.5929944 -1.017495 -0.530459}>>> grouped<pandas.core.groupby.DataFrameGroupBy object at 0x041288F0>>>> list(grouped)[(dtype('float64'), data1 data20 -0.410673 0.5193781 -2.120793 0.1990742 0.642216 -0.1436713 0.975133 -0.5929944 -1.017495 -0.530459), (dtype('O'), key1 key20 a one1 a two2 b one3 b two4 a one)]




6、选取一个或一组列
对于由DataFrame产生的GroupBy对象,如果用一个(单个字符串)或一组(字符串数组)列名对其进行索引,就能实现选取部分列进行聚合的目的,即:

>>> df.groupby('key1')['data1']<pandas.core.groupby.SeriesGroupBy object at 0x06615FD0>>>> df.groupby('key1')['data2']<pandas.core.groupby.SeriesGroupBy object at 0x06615CB0>>>> df.groupby('key1')[['data2']]<pandas.core.groupby.DataFrameGroupBy object at 0x06615F10>和以下代码是等效的:
>>> df['data1'].groupby([df['key1']])<pandas.core.groupby.SeriesGroupBy object at 0x06615FD0>>>> df[['data2']].groupby([df['key1']])<pandas.core.groupby.DataFrameGroupBy object at 0x06615F10>>>> df['data2'].groupby([df['key1']])<pandas.core.groupby.SeriesGroupBy object at 0x06615E30>尤其对于大数据集,很可能只需要对部分列进行聚合。例如,在前面那个数据集中,如果只需计算data2列的平均值并以DataFrame形式得到结果,代码如下:

>>> df.groupby(['key1', 'key2'])[['data2']].mean() data2key1 key2 a one -0.005540 two 0.199074b one -0.143671 two -0.592994>>> df.groupby(['key1', 'key2'])['data2'].mean()key1 key2a one -0.005540 two 0.199074b one -0.143671 two -0.592994Name: data2, dtype: float64这种索引操作所返回的对象是一个已分组的DataFrame(如果传入的是列表或数组)或已分组的Series(如果传入的是标量形式的单个列明):
>>> s_grouped = df.groupby(['key1', 'key2'])['data2']>>> s_grouped<pandas.core.groupby.SeriesGroupBy object at 0x06615B10>>>> s_grouped.mean()key1 key2a one -0.005540 two 0.199074b one -0.143671 two -0.592994Name: data2, dtype: float64




7、通过字典或Series进行分组
除数组以外,分组信息还可以其他形式存在,来看一个DataFrame示例:

>>> people = pd.DataFrame(np.random.randn(5, 5),... columns=['a', 'b', 'c', 'd', 'e'],... index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis']... )>>> people a b c d eJoe 0.306336 -0.139431 0.210028 -1.489001 -0.172998Steve 0.998335 0.494229 0.337624 -1.222726 -0.402655Wes 1.415329 0.450839 -1.052199 0.731721 0.317225Jim 0.550551 3.201369 0.669713 0.725751 0.577687Travis -2.013278 -2.010304 0.117713 -0.545000 -1.228323>>> people.ix[2:3, ['b', 'c']] = np.nan#.ix[]见63条,.nan见64条假设已知列的分组关系,并希望根据分组计算列的总计:

>>> mapping = {'a':'red', 'b':'red', 'c':'blue',... 'd':'blue', 'e':'red', 'f':'orange'}>>> mapping{'a': 'red', 'c': 'blue', 'b': 'red', 'e': 'red', 'd': 'blue', 'f': 'orange'}>>> type(mapping)<type 'dict'>现在,只需将这个字典传给groupby即可:
>>> by_column = people.groupby(mapping, axis=1)#axis=1代表列>>> by_column<pandas.core.groupby.DataFrameGroupBy object at 0x066150F0>>>> by_column.sum() blue redJoe -1.278973 -0.006092Steve -0.885102 1.089908Wes 0.731721 1.732554Jim 1.395465 4.329606Travis -0.427287 -5.251905Series也有同样的功能,它可以被看做一个固定大小的映射。对于上面那个例子,如果用Series作为分组键,则pandas会检查Series以确保其索引跟分组轴是对齐的:
>>> map_series = pd.Series(mapping)>>> map_seriesa redb redc blued bluee redf orangedtype: object>>> people.groupby(map_series, axis=1).count() blue redJoe 2 3Steve 2 3Wes 1 2Jim 2 3Travis 2 3


8、通过函数进行分组
相较于字典或Series,Python函数在定义分组映射关系时可以更有创意且更为抽象。任何被当做分组键的函数都会在各个索引值上被调用一次,其返回值就会被用作分组名称。
具体点说,以DataFrame为例,其索引值为人的名字。假设你希望根据人名的长度进行分组,虽然可以求取一个字符串长度数组,但其实仅仅传入len函数即可:

>> people.groupby(len).sum() a b c d e3 2.272216 3.061938 0.879741 -0.031529 0.7219145 0.998335 0.494229 0.337624 -1.222726 -0.4026556 -2.013278 -2.010304 0.117713 -0.545000 -1.228323将函数跟数组、列表、字典、Series混合使用也不是问题,因为任何东西最终都会被转换为数组:
>>> key_list = ['one', 'one', 'one', 'two', 'two']>>> people.groupby([len, key_list]).min() a b c d e3 one 0.306336 -0.139431 0.210028 -1.489001 -0.172998 two 0.550551 3.201369 0.669713 0.725751 0.5776875 one 0.998335 0.494229 0.337624 -1.222726 -0.4026556 two -2.013278 -2.010304 0.117713 -0.545000 -1.228323


9、根据索引级别分组
层次化索引数据集最方便的地方在于它能够根据索引级别进行聚合。要实现该目的,通过level关键字传入级别编号或名称即可:

>>> columns = pd.MultiIndex.from_arrays([['US', 'US', 'US', 'JP', 'JP'],... [1, 3, 5, 1, 3]], names=['cty', 'tenor'])>>> columnsMultiIndex[US 1, 3, 5, JP 1, 3]>>> hier_df = pd.DataFrame(np.random.randn(4, 5), columns=columns)>>> hier_dfcty US JP tenor 1 3 5 1 30 -0.166600 0.248159 -0.082408 -0.710841 -0.0971311 -1.762270 0.687458 1.235950 -1.407513 1.3040552 1.089944 0.258175 -0.749688 -0.851948 1.6877683 -0.378311 -0.078268 0.247147 -0.018829 0.744540>>> hier_df.groupby(level='cty', axis=1).count()cty JP US0 2 31 2 32 2 33 2 3
58. .fillna()
59. .sum(1), numpy.argsort()
60. .take()
61. .plot()
62. .div()
63. .ix() 切片可以这么理解:DataFrame 对象的标准切片语法为:.ix[::,::]。ix 对象可以接受两套切片,分别为行(axis=0)和列(axis=1)的方向:>>> df Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> df.ix[:2,:2] Ohio Texasa 0 1c 3 4[2 rows x 2 columns]>>> df.ix['a','Ohio']0
64. .nan
处理缺失数据
pandas 中 NA 的主要表现为 np.nan,另外 Python 内建的 None 也会被当做 NA 处理。处理 NA 的方法有四种:dropna , fillna , isnull , notnullis(not)null这一对方法对对象做元素级应用,然后返回一个布尔型数组,一般可用于布尔型索引。dropna对于一个 Series,dropna 返回一个仅含非空数据和索引值的 Series。问题在于对 DataFrame 的处理方式,因为一旦 drop 的话,至少要丢掉一行(列)。这里的解决方式与前面类似,还是通过一个额外的参数:dropna(axis=0, how='any', thresh=None),how 参数可选的值为 any 或者 all。all 仅在切片元素全为 NA 时才抛弃该行(列)。另外一个有趣的参数是 thresh,该参数的类型为整数,它的作用是,比如 thresh=3,会在一行中至少有 3 个非 NA值时将其保留。fillnafillna(value=None, method=None, axis=0)中的 value 参数除了基本类型外,还可以使用字典,这样可以实现对不同的列填充不同的值。method 的用法与前面.reindex()方法相同,这里不再赘述。
inplace 参数
前面有个点一直没讲,结果整篇示例写下来发现还挺重要的。就是 Series 和 DataFrame 对象的方法中,凡是会对数组作出修改并返回一个新数组的,往往都有一个replace=False的可选参数。如果手动设定为 True,那么原数组就可以被替换。
---
重新索引Series 对象的重新索引通过其.reindex(index=None,**kwargs)方法实现。**kwargs中常用的参数有俩:method=None,fill_value=np.NaNser = Series([4.5,7.2,-5.3,3.6],index=['d','b','a','c'])>>> a = ['a','b','c','d','e']>>> ser.reindex(a)a -5.3b 7.2c 3.6d 4.5e NaNdtype: float64>>> ser.reindex(a,fill_value=0)a -5.3b 7.2c 3.6d 4.5e 0.0dtype: float64>>> ser.reindex(a,method='ffill')a -5.3b 7.2c 3.6d 4.5e 4.5dtype: float64>>> ser.reindex(a,fill_value=0,method='ffill')a -5.3b 7.2c 3.6d 4.5e 4.5dtype: float64.reindex()方法会返回一个新对象,其 index 严格遵循给出的参数,method:{'backfill', 'bfill', 'pad', 'ffill', None}参数用于指定插值(填充)方式,当没有给出时,自动用fill_value填充,默认为 NaN(ffill = pad,bfill = back fill,分别指插值时向前还是向后取值)
65. .pivot_table()DataFrame.pivot_table('value1', index='column1', columns = 'column2', aggfunc = '运算方法 比如mean')
例:mean_ratings = data.pivot_table('rating', index ='title', columns = 'gender', aggfunc ='mean')
66. .sort_values()DataFrame.sort_values( by = 'value1 of column1', ascending = False)对于DataFrame进行筛选和排序,将column1中值为value1的挑出来,并做降序排序(即ascending = False,若ascending = True则为升序排序)
例:top_female_ratings = mean_ratings.sort_values(by = 'F', ascending = False)
67. 类比 .groupby(), .pivot_table(), .sort_values()
.groupby() 和 .pivot_table() 是很类似的,目的都是聚类,然后分析
sort_values() 主要优势体现在排序
68. .read_csv(path, names)txt文件中,用非常标准的逗号隔开信息,用pandas.read_csv将其加载到DataFrame中columns = ['name', 'sex', 'births']path = 'data/ch02/names/yob%d.txt' %yearframe = pd.read_csv(path, names = columens)
69.lambda(), filter(), map(), reduce()1、lambda()lambda()是Python里的匿名函数,其语法如下:lambda [arg1[, arg2, ... argN]]: expression下面是个1+2=3的例子>>> fun = lambda x,y:x+y>>> fun(1,2)3>>> (lambda x,y:x+y)(1,2)32、filter()filter(function, sequence):目的:筛选出数列sequence中,符合判决式function的元素。其中function的返回结果为bool类型:True or Falsesequence的类型为:List/String/Tuple最终结果,为sequence中的元素,长度比sequence短或一样
>>> def f(x): return x % 2 != 0 and x % 3 != 0>>> filter(f, range(2, 10))[5, 7]>>> def f(x): return x != 'a'>>> filter(f, "abcdef")'bcdef'3、map()map(function, sequence) :对于sequence中的各个元素,分别用function中的函数运算一遍。其中:function的返回格式任意sequence类型为: List/ String/ Tuple最终结果为function计算结果,长度与sequence一样。
>>> def cube(x): return x*x*x>>> map(cube, range(1, 11))[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def f(x): return x % 2 != 0 and x % 3 != 0>>> map(f, range(2, 10))[False, False, False, True, False, True, False, False]
>>> def cube(x): return x*x*x>>> filter(cube, range(1, 11))[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> def cube(x) : return x + x>>> map(cube , "abcde")['aa', 'bb', 'cc', 'dd', 'ee']另外map也支持多个sequence,这就要求function也支持相应数量的参数输入:>>> def add(x, y): return x+y>>> map(add, range(8), range(8))[0, 2, 4, 6, 8, 10, 12, 14]
4、reduce()reduce(function, sequence, starting_value):function中至少包含两个元素,sequence的类型为:List/String/Tuple,reduce()的目的:sequence中选取两个元素,做运算,结果再与接下来的元素继续运算。sequence所有元素运算完之后,再将结果与starting_value进行两两运算。结果为一个数值
例如可以用来对List求和:>>> def add(x,y): return x + y>>> reduce(add, range(1, 11))55 (注:1+2+3+4+5+6+7+8+9+10)>>> reduce(add, range(1, 11), 20)75 (注:1+2+3+4+5+6+7+8+9+10+20)5、综合例子下面是两个综合利用以上四个函数的例子:例子1:计算5!+4!+3!+2!+1!a=[5,4,3,2,1]def fun(x): result = 1 while x >= 1: result = result * x x = x - 1 return resultprint reduce(lambda x,y:x+y, map(fun,a))
例子2:将100以内的质数挑选出来import math def isPrime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return Trueprint filter(isPrime,range(1,100))
70. .reindex()DataFrame.reindex(columns, level)
71. .T用于矩阵转置numpy.ndarray.Tndarray.TSame as self.transpose(), except that self is returned if self.ndim < 2.Examples>>>>>>x= np.array([[1.,2.],[3.,4.]])>>>xarray([[ 1., 2.], [ 3., 4.]])>>>x.Tarray([[ 1., 3.], [ 2., 4.]])>>>x= np.array([1.,2.,3.,4.])>>>xarray([ 1., 2., 3., 4.])>>>x.Tarray([ 1., 2., 3., 4.])
72.pandas.DataFrame.div
计算DataFrame中的元素和other的商,返回值仍为DataFrame
DataFrame.div(other,axis='columns',level=None,fill_value=None)[source]Floating division of dataframe and other, element-wise (binary operatortruediv).Equivalent todataframe/other, but with support to substitute a fill_value for missing data in one of the inputs.

例:dfOut[11]: a bx 1 11y 2 12z 4 3w 5 22
df.div(df.sum(1),axis=0) #df.sum(1)是对于每行求和,axis=0是每行求div运算Out[14]: a bx 0.083333 0.916667y 0.142857 0.857143z 0.571429 0.428571w 0.185185 0.814815
df.div(df.sum(1),axis=1)Out[17]: a b w x y zx NaN NaN NaN NaN NaN NaNy NaN NaN NaN NaN NaN NaNz NaN NaN NaN NaN NaN NaNw NaN NaN NaN NaN NaN NaN
df.div(df.sum(0),axis=1) #对每列求和,每个值再除以每列的和,求比例Out[27]: a bx 0.083333 0.229167y 0.166667 0.250000z 0.333333 0.062500w 0.416667 0.458333

df.div(df.sum()) #默认sum(0), axis=1,每列求和,求比例Out[38]: a bx 0.083333 0.229167y 0.166667 0.250000z 0.333333 0.062500w 0.416667 0.458333
73. DataFrame.sumDF.sum() 计算每列的和值,等效于DF.sum(0)DF.sum(1)计算每行的和值
例:table[:10]Out[4]: sex F Myear 1880 8.0 79.01881 11.0 92.01882 9.0 128.01883 7.0 125.01884 15.0 125.01885 10.0 122.01886 8.0 136.01887 12.0 166.01888 23.0 175.01889 23.0 155.0
table.sum()[:10]Out[5]: sexF 303512.0M 114017.0dtype: float64
table.sum(1)[:10]Out[6]: year1880 87.01881 103.01882 137.01883 132.01884 140.01885 132.01886 144.01887 178.01888 198.01889 178.0dtype: float64
table.sum(0)[:10]Out[7]: sexF 303512.0M 114017.0dtype: float64
74. DataFrame改变列的名称
DataFrame.columns = ['x', 'y', ...]DataFrame.index = [...] #改变行名
75. import 模块,模块如果变动,需要重新加载,甚至重启IPython
import some_libdreload (some_lib)#dreload 解决模块深度(递归)重加载
x = 5y = [1,2,3,4]result = some_lib.get_answer(x, y)


第四章
76.reshape((x,y)) 将行列式重排,总元素数量保持不变
77.花式索引是将数据复制到新数组中,切片只索引,不复制
例:arr =array([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19],[20, 21, 22, 23],[24, 25, 26, 27],[28, 29, 30, 31]])arr[np.ix_([1,5,7,2],[0,3,1,2])] 花式索引第1, 5,7,2行,第0,3,1,2列的数据等效于arr[[1,5,7,2]] [ : , [0,3,1,2]]
结果:array([[ 11., 11., 11., 11.],[ 15., 15., 15., 15.],[ 17., 17., 17., 17.],[ 12., 12., 12., 12.]])


arr[[1,5,7,2],[ 0,3,1,2 ]]的结果是:array([ 11., 15., 17., 12.])

78. 拆分数字的小数部分和整数部分
np.modf([1.2,-3.4])Out[68]: (array([ 0.2, -0.4]), array([ 1., -3.]))
79.numpy.random.randn(x,y)生成一个x行y列的矩阵,再随机生成一些数字填进去。生产的数字,符合N(0,1)分布,中心值为0,标准差为1,正太分布
numpy.random.randn(n)随机产生n个数字,分布满足N(0,1)NotesFor random samples from, use:sigma*np.random.randn(...)+muExamples>>>>>>np.random.randn()2.1923875335537315 #randomTwo-by-four array of samples from N(3, 6.25):>>>>>>2.5* np.random.randn(2,4)+3 #产生的分布为 N(3, 2.5^2)a * np.random.randn(n) + b #产生n个数字,满足 N(b, a^2)分布,std = a, mean =barray([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], #random [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random
80.点乘和叉乘
矩阵的点乘arr = np.arrange(32).reshape((8,4))production1 = np.doc(arr.T, arr)

叉乘对于向量适用x = [1,2,3]y=[4,5,6]np.cross(x,y)
Out[13]: array([-3, 6, -3])
81. 数学和统计方法
arr2 = np.arange(32).reshape((8,4))Out[16]: array([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19],[20, 21, 22, 23],[24, 25, 26, 27],[28, 29, 30, 31]])
arr2.mean(axis=1)#将沿着轴1计算,矩阵变为axis=0方向的矩阵,维度减1Out[17]: array([ 1.5, 5.5, 9.5, 13.5, 17.5, 21.5, 25.5, 29.5])
arr2.mean(1)Out[22]: array([ 1.5, 5.5, 9.5, 13.5, 17.5, 21.5, 25.5, 29.5])
82.numpy.unique(matrix) 等价于 sorted(set(matrix))
names = np.array(['Will','Joe','Bob','Will','Joe','Bob','Joe'])
np.unique(names)Out[39]: array(['Bob', 'Joe', 'Will'],dtype='|S4')
sorted(set(names))Out[40]: ['Bob', 'Joe', 'Will']
83. np.in1d
values = np.array([6,0,0,3,2,5,6])
np.in1d(values, [2,3,6])Out[42]: array([ True, False, False, True, True, False, True], dtype=bool)
84. 读取保存文件
np.save('file_name', array)np.sacez('file_name.npz', a=array1, b=array2)
x = np.load('file_name.npz')x['a']
读取文本文件:pandas:read_csvread_table
numpy:np.loadtxt('file_name.txt', delimiter=',')np.savetxt('file_name.txt', array)
!type file_name.txt//在IPython,打开文件
np.genfromtxt
85. 矩阵--求逆、行列式
numpy.linalg 中的矩阵算法库Fortran:BLAS、LAPACK、Intel MKL
求矩阵的逆矩阵: inv(matrix)
行列式变换为上三角矩阵:q, r = qr(mat)r 为上三角矩阵q 为行列式变换,q的行列式值为1

85. 随机数生产
np.random.normal(loc = mean, scale = std_ev., size=(x, y))


85. np.where
np.where(condition, x, y)condition为 bool类型x 和 y 可以为数组、数字或其他类型
86.numpy.cumsum(a,axis=None,dtype=None,out=None)沿着给定的轴,进行逐步加和计算

Examples>>>>>>a= np.array([[1,2,3], [4,5,6]])>>>aarray([[1, 2, 3], [4, 5, 6]])>>>np.cumsum(a)array([ 1, 3, 6, 10, 15, 21])>>>np.cumsum(a, dtype=float)# specifies type of output value(s)array([ 1., 3., 6., 10., 15., 21.])>>>>>>np.cumsum(a,axis=0)# sum over rows for each of the 3 columnsarray([[1, 2, 3], [5, 7, 9]])>>>np.cumsum(a,axis=1)# sum over columns for each of the 2 rowsarray([[ 1, 3, 6], [ 4, 9, 15]])
87. numpy.argmax(a,axis=None,out=None)
返回沿着某一方向,最大值的第一个位置
例:a = [[10,11,9],[15,6,7]]
np.argmax(a)Out[11]: 3
np.argmax(a,axis=0)Out[12]: array([1, 0, 0], dtype=int64)
np.argmax(a,axis=1)Out[13]: array([1, 0], dtype=int64)
b = [0, 5, 2, 3, 4, 5]
np.argmax(b)Out[15]: 1
利用该函数,可以求得矩阵,满足某一条件的第一个位置:
例:walk = [1,5,10,11,5,10,12](np.abs(walk)>=10).argmax()
Out[24]: 2

第五章

5.1 Series
obj2 = Series([4,7,-5,3], index=['d','b','a','c'])
np.exp(obj2)
从字典直接转化为SeriesSeries_1 = Series(dict1)
从Series库中节选部分内容
例:import pandas as pd; import numpy as npfrom pandas import Series, DataFrame
sdata = {'Ohio':35000, 'Texas':71000, 'Oregon':16000, 'Utah':5000}obj3 = Series(sdata)states = ['CA', 'Ohio','Oregon', 'Texas']obj4 = Series(sdata, index=states)
obj3Out[3]: Ohio 35000Oregon 16000Texas 71000Utah 5000dtype: int64
obj4Out[4]: CA NaNOhio 35000.0Oregon 16000.0Texas 71000.0dtype: float64

5.2 DataFrame
DF = DataFrame(dict_1, columns = ['y1','y2',...], index = ['x1', 'x2',..])


5.3 Series 的工具
reindex, fill_value, ffill

例:obj = Series([4.5,7.2,-5.3,3.6], index = ['d','b','a','c'])obj5 = obj.reindex(['a','b','c','d','e'],fill_value=0)
obj6 = Series(['blue','purple','yellow'], index=[0,2,4])obj7 = obj6.reindex(range(6), method = 'ffill')
输出:objOut[9]: d 4.5b 7.2a -5.3c 3.6dtype: float64
obj5Out[10]: a -5.3b 7.2c 3.6d 4.5e 0.0dtype: float64
obj6Out[11]: 0 blue2 purple4 yellowdtype: object
obj7Out[12]: 0 blue1 blu2 purple3 purple4 yellow5 yellowdtype: object
5.4 丢弃指定轴上的项
data = DataFrame(np.arange(16).reshape((4,4)), index=['Ohio','Colorado','Utah','New York'],columns=['one','two','three','four'])
data1 = data.drop(['Colorado', 'Ohio'])data2 = data.drop(['two', 'four'], axis=1)
输出dataOut[20]: one two three fourOhio 0 1 2 3Colorado 4 5 6 7Utah 8 9 10 11New York 12 13 14 15
data1Out[21]: one two three fourUtah 8 9 10 11New York 12 13 14 15
data2Out[22]: one threeOhio 0 2Colorado 4 6Utah 8 10New York 12 14
5.5 索引
DataFrame 的索引 ix

例:data = DataFrame(np.arange(16).reshape((4,4)), index=['Ohio','Colorado','Utah','New York'],columns=['one','two','three','four'])
data3 = data.ix['Colorado',['two','three']]data4 = data.ix[['Colorado','Utah'],[3,0,1]]data5 = data.ix[data.three>5, :3]
输出:dataOut[26]: one two three fourOhio 0 1 2 3Colorado 4 5 6 7Utah 8 9 10 11New York 12 13 14 15
data3Out[24]: two 5three 6Name: Colorado, dtype: int32
data4Out[25]: four one twoColorado 7 4 5Utah 11 8 9
data5Out[29]: one two threeColorado 4 5 6Utah 8 9 10New York 12 13 14
5.6 DataFrame 算术运算和数据对齐

例:df1 = DataFrame(np.arange(12).reshape((3,4)), columns = list('abcd'))df2 = DataFrame(np.arange(20).reshape((4,5)), columns = list('abcde'))
sum1 = df1+df2sum2 = df1.add(df2, fill_value=0)
结果:df1Out[32]: a b c d0 0 1 2 31 4 5 6 72 8 9 10 11
df2Out[33]: a b c d e0 0 1 2 3 41 5 6 7 8 92 10 11 12 13 143 15 16 17 18 19
sum1Out[34]: a b c d e0 0.0 2.0 4.0 6.0 NaN1 9.0 11.0 13.0 15.0 NaN2 18.0 20.0 22.0 24.0 NaN3 NaN NaN NaN NaN NaN
sum2Out[35]: a b c d e0 0.0 2.0 4.0 6.0 4.01 9.0 11.0 13.0 15.0 9.02 18.0 20.0 22.0 24.0 14.03 15.0 16.0 17.0 18.0 19.0
DataFrame 和 Series之间的运算,遵循 “广播”的规律
例:arr = np.arange(12).reshape((3,4))arr_minus=arr-arr[0]
输出:arrOut[37]: array([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11]])
arr[0]Out[38]: array([0, 1, 2, 3])
arr_minusOut[39]: array([[0, 0, 0, 0],[4, 4, 4, 4],[8, 8, 8, 8]])
例:frame = DataFrame(np.arange(12).reshape((4,3)), columns = list('bde'), index = ['Utah','Ohio','Texas','Oregon'])series3 = frame['d']series2 = Series(range(3), index=['b','e','f'])
f_sub = frame.sub(series3, axis=0)f_sub2 = frame-series2
输出:frameOut[51]: b d eUtah 0 1 2Ohio 3 4 5Texas 6 7 8Oregon 9 10 11
series3Out[52]: Utah 1Ohio 4Texas 7Oregon 10Name: d, dtype: int32
series2Out[53]: b 0e 1f 2dtype: int64
f_subOut[54]: b d eUtah -1 0 1Ohio -1 0 1Texas -1 0 1Oregon -1 0 1
f_sub2Out[55]: b d e fUtah 0.0 NaN 1.0 NaNOhio 3.0 NaN 4.0 NaNTexas 6.0 NaN 7.0 NaNOregon 9.0 NaN 10.0 NaN
5.7 函数应用和映射
frame = DataFrame(np.arange(12).reshape((4,3)), columns = list('bde'), index =
f = lambda x: x.max()- x.min()
f1 = frame.apply(f)#DataFrame.apply(function) 对于矩阵行列式求解 用.apply()f2 = frame.apply(f, axis=1)
g = lambda x : '%.2f' %xg1 = frame.applymap(g)#.applymap() 适用于矩阵的元素级计算
结果:frameOut[57]: b d eUtah 0 1 2Ohio 3 4 5Texas 6 7 8Oregon 9 10 11
f1Out[58]: b 9d 9e 9dtype: int64
f2Out[59]: Utah 2Ohio 2Texas 2Oregon 2dtype: int64
5.8 搜索
DataFrame.sort_index(axis=0 or 1, ascending = True or False)
默认axis =0 按index排序ascending =True 升序
frame.sort_index( by = ['a', 'b']) #先按照 b 列排一次,再按照 a 列排一次
5.9 排名 -- 类似于sort_index,给出元素在序列中排第几位
numpy.argsort()Series.rank(ascending = True or False, method = ' ' or 'first' or 'max')
ascending = True 降序(默认)method = ‘ ' (默认) 降序,相同的元素,取平均值,相同元素排位相同method = 'first' 降序,相同的元素,按照从前到后的顺序,排位递增method = 'max' 升序,相同的元素,排位相同
DataFrame.rank(axis = ' x')


obj_rank = Series([7, -5,7,4,2,0,4])
o1 = obj_rank.rank()o2 = obj_rank.rank(method = 'first')o3 = obj_rank.rank(ascending=False, method = 'max')
输出:obj_rankOut[65]: 0 71 -52 73 44 25 06 4dtype: int64
o1Out[66]: 0 6.51 1.02 6.53 4.54 3.05 2.06 4.5dtype: float64
o2Out[67]: 0 6.01 1.02 7.03 4.04 3.05 2.06 5.0dtype: float64
o3Out[68]: 0 2.01 7.02 2.03 4.04 5.05 6.06 4.0dtype: float64

5.10 滤除缺失数据
dropna对于一个 Series,dropna 返回一个仅含非空数据和索引值的 Series。问题在于对 DataFrame 的处理方式,因为一旦 drop 的话,至少要丢掉一行(列)。这里的解决方式与前面类似,还是通过一个额外的参数:dropna(axis=0, how='any', thresh=None),how 参数可选的值为 any 或者 all。all 仅在切片元素全为 NA 时才抛弃该行(列)。另外一个有趣的参数是 thresh,该参数的类型为整数,它的作用是,比如 thresh=3,会在一行中至少有 3 个非 NA值时将其保留。
例:df = DataFrame(np.random.randn(7,3))df.ix[:4,1]= nan; df.ix[:2,2]= nan
df_dropna = df.dropna(thresh=2) #滤出,行元素中至少两个非NAN的行
输出:dfOut[10]: 0 1 20 0.835553 NaN NaN1 0.664646 NaN NaN2 -1.201019 NaN NaN3 -1.317435 NaN 0.0768794 0.701371 NaN -1.0100315 -0.944616 0.195193 -0.3515686 -0.985893 -0.317615 -0.597908
df_dropnaOut[11]: 0 1 23 -1.317435 NaN 0.0768794 0.701371 NaN -1.0100315 -0.944616 0.195193 -0.3515686 -0.985893 -0.317615 -0.597908
5.11 填充缺失数据
DataFrame.fillna(method = 'ffill', limit = 2)ffill 赋值前面的元素limit =2 最多复制2行
5.12 MultiIndex 型的Series 和 DataFrame相互转化
Series.unstack() --> DataFrameDataFrame.stack() -- Series, 其中Series的Key变为DataFrame的列头
例:result = pd.concat([s1,s1,s3], keys = ['one','two','three'])df15=result.unstack()
输出:resultOut[53]: one a 0b 1two a 0b 1three f 5g 6dtype: int64
df15Out[54]: a b f gone 0.0 1.0 NaN NaNtwo 0.0 1.0 NaN NaNthree NaN NaN 5.0 6.0
例:data = Series(np.random.randn(10), index=[['a','a','a','b','b','b','c','c','d','d'],[1,2,3,1,2,3,1,2,2,3]])
DF_data = data.unstack()Se_data = DF_data.stack()
输出:dataOut[14]: a 1 0.6674912 -0.8607223 -0.082258b 1 -1.5178582 1.5023913 -1.141736c 1 1.0595832 0.734676d 2 0.2458173 -1.397910dtype: float64
DF_dataOut[15]: 1 2 3a 0.667491 -0.860722 -0.082258b -1.517858 1.502391 -1.141736c 1.059583 0.734676 NaNd NaN 0.245817 -1.397910
Se_dataOut[16]: a 1 0.6674912 -0.8607223 -0.082258b 1 -1.5178582 1.5023913 -1.141736c 1 1.0595832 0.734676d 2 0.2458173 -1.397910dtype: float64
5.13 DataFrame交换index
frame.swaplevel('key1', 'key2')
5.14 面板数据 Panel
我的理解是比普通DataFrame,维度更高的数据结构,无法像DataFrame一样输出数据结构。只能大概表示基本形式。Panel转化为DataFrame: Panel.to_frame()DataFrame转化为Panel: DataFrame.to_panel()
例:
import pandas.io.data as webimport pandas as pd; import numpy as np;
pdata = pd.Panel(dict((stk, web.get_data_yahoo(stk, '1/1/2009', '6/1/2012')) for stk in ['AAPL','GOOG','MSFT','DELL']))#pandas.io.data.get_data_yahoo( ... )是作者自己写的一个工具,用于后台抓取雅虎财经的股票信息
pdata2 = pdata.swapaxes('items', 'minor')pdata3 = pdata2['Adj Close']
pdata4 = pdata2.ix[:, '6/1/2012',:]pdata5 = pdata2.ix['Adj Close', '5/22/2012':, :]
stacked = pdata2.ix[:, '5/30/2012':, :].to_frame()
pdata6 = stacked.to_panel()
输出结果:pdataOut[11]: <class 'pandas.core.panel.Panel'>Dimensions: 4 (items) x 868 (major_axis) x 6 (minor_axis)Items axis: AAPL to MSFTMajor_axis axis: 2009-01-02 00:00:00 to 2012-06-01 00:00:00Minor_axis axis: Open to Adj Close
pdata2Out[12]: <class 'pandas.core.panel.Panel'>Dimensions: 6 (items) x 868 (major_axis) x 4 (minor_axis)Items axis: Open to Adj CloseMajor_axis axis: 2009-01-02 00:00:00 to 2012-06-01 00:00:00Minor_axis axis: AAPL to MSFT
pdata3Out[13]: AAPL DELL GOOG MSFTDate 2009-01-02 11.808505 10.39902 160.499779 16.5013032009-01-05 12.306869 10.26359 163.861421 16.6555212009-01-06 12.103880 10.68922 166.863420 16.8503232009-01-07 11.842336 10.78596 160.844427 15.8357322009-01-08 12.062241 10.90204 162.432840 16.3308532009-01-09 11.786384 10.75694 157.377899 15.8438492009-01-12 11.536551 10.30228 156.189080 15.8032642009-01-13 11.412936 10.40869 157.003261 16.0873502009-01-14 11.103247 9.97338 150.334921 15.4948292009-01-15 10.849511 10.19587 149.345914 15.6165802009-01-16 10.712884 9.93469 149.685575 15.9980662009-01-20 10.175483 9.52840 141.234014 14.9997092009-01-21 10.777944 9.86697 151.388865 15.7302142009-01-22 11.497515 9.65416 153.097158 13.8877182009-01-23 11.497515 9.80893 162.188089 13.9607692009-01-26 11.664070 9.97338 161.773501 14.3097872009-01-27 11.805902 9.74122 165.574702 14.3341372009-01-28 12.257423 10.52477 174.161139 14.6425742009-01-29 12.101278 9.62514 171.488809 14.2773212009-01-30 11.727830 9.18983 169.096191 13.8796012009-02-02 11.907397 9.00603 170.115172 14.4721222009-02-03 12.098675 9.45101 170.055239 15.0159432009-02-04 12.172844 9.47036 171.328962 15.1214592009-02-05 12.551497 9.12212 176.683613 15.4542462009-02-06 12.975692 9.15114 185.454867 15.9574832009-02-09 13.338731 9.32526 189.196135 15.7789152009-02-10 12.729764 8.86093 179.076231 15.2594442009-02-11 12.598341 8.72550 178.841472 15.5922292009-02-12 12.917138 8.87060 181.343964 15.6328142009-02-13 12.902825 8.82224 178.661643 15.494829... ... ... ...2012-04-23 74.390324 15.57434 298.502008 28.1457762012-04-24 72.904343 15.65173 300.335186 27.9705232012-04-25 79.373975 15.88390 304.555978 28.2158792012-04-26 79.074692 15.99030 307.428105 28.1370152012-04-27 78.463126 15.90324 307.183354 28.0230992012-04-30 75.988215 15.83553 302.123410 28.0581502012-05-01 75.747494 15.86455 301.913607 28.0493862012-05-02 76.248456 15.64689 303.327209 27.8653702012-05-03 75.707153 15.70010 305.205309 27.8303202012-05-04 73.551045 15.29381 298.187334 27.1468292012-05-07 74.101459 15.30348 303.472045 26.8576602012-05-08 73.932300 15.19708 306.089446 26.7262202012-05-09 74.062425 15.15838 304.271262 26.9540512012-05-10 74.236781 15.04230 306.524016 26.9365252012-05-11 73.741023 14.91654 302.313200 27.3045582012-05-14 72.636291 14.93589 301.698816 26.8839492012-05-15 71.979179 14.83916 305.250263 26.6458032012-05-16 71.056621 14.52477 314.151389 26.3723782012-05-17 68.979886 14.45222 311.214326 26.2136142012-05-18 69.013715 14.25875 299.900615 25.8167072012-05-21 73.034461 14.48124 306.748784 26.2400752012-05-22 72.473644 14.58765 300.100412 26.2488962012-05-23 74.241986 12.08221 304.426106 25.6755842012-05-24 73.560156 12.04351 301.528978 25.6403022012-05-25 73.165884 12.05319 295.470050 25.6314822012-05-28 NaN 12.05319 NaN NaN2012-05-29 74.464493 12.24666 296.873645 26.0724912012-05-30 75.362333 12.14992 293.821674 25.8784482012-05-31 75.174961 11.92743 290.140354 25.7461452012-06-01 72.996726 11.67592 285.205295 25.093451
[868 rows x 4 columns]
pdata4Out[14]: Open High Low Close Volume Adj CloseAAPL 569.159996 572.650009 560.520012 560.989983 130246900.0 72.996726DELL 12.150000 12.300000 12.045000 12.070000 19397600.0 11.675920GOOG 571.790972 572.650996 568.350996 570.981000 6138700.0 285.205295MSFT 28.760000 28.959999 28.440001 28.450001 56634300.0 25.093451
pdata5Out[15]: AAPL DELL GOOG MSFTDate 2012-05-22 72.473644 14.58765 300.100412 26.2488962012-05-23 74.241986 12.08221 304.426106 25.6755842012-05-24 73.560156 12.04351 301.528978 25.6403022012-05-25 73.165884 12.05319 295.470050 25.6314822012-05-28 NaN 12.05319 NaN NaN2012-05-29 74.464493 12.24666 296.873645 26.0724912012-05-30 75.362333 12.14992 293.821674 25.8784482012-05-31 75.174961 11.92743 290.140354 25.7461452012-06-01 72.996726 11.67592 285.205295 25.093451
stackedOut[16]: Open High Low Close Volume \Date minor 2012-05-30 AAPL 569.199997 579.989990 566.559990 579.169998 132357400.0DELL 12.590000 12.700000 12.460000 12.560000 19787800.0GOOG 588.161028 591.901014 583.530999 588.230992 3827600.0MSFT 29.350000 29.480000 29.120001 29.340000 41585500.02012-05-31 AAPL 580.740021 581.499985 571.460022 577.730019 122918600.0DELL 12.530000 12.540000 12.330000 12.330000 19955600.0GOOG 588.720982 590.001032 579.001013 580.860990 5958800.0MSFT 29.299999 29.420000 28.940001 29.190001 39134000.02012-06-01 AAPL 569.159996 572.650009 560.520012 560.989983 130246900.0DELL 12.150000 12.300000 12.045000 12.070000 19397600.0GOOG 571.790972 572.650996 568.350996 570.981000 6138700.0MSFT 28.760000 28.959999 28.440001 28.450001 56634300.0
Adj Close Date minor 2012-05-30 AAPL 75.362333DELL 12.149920GOOG 293.821674MSFT 25.8784482012-05-31 AAPL 75.174961DELL 11.927430GOOG 290.140354MSFT 25.7461452012-06-01 AAPL 72.996726DELL 11.675920GOOG 285.205295MSFT 25.093451
pdata6Out[17]: <class 'pandas.core.panel.Panel'>Dimensions: 6 (items) x 3 (major_axis) x 4 (minor_axis)Items axis: Open to Adj CloseMajor_axis axis: 2012-05-30 00:00:00 to 2012-06-01 00:00:00Minor_axis axis: AAPL to MSFT
type(pdata)Out[18]: pandas.core.panel.Panel
type(pdata2)Out[19]: pandas.core.panel.Panel
type(pdata3)Out[20]: pandas.core.frame.DataFrame
type(pdata4)Out[21]: pandas.core.frame.DataFrame
type(pdata5)Out[22]: pandas.core.frame.DataFrame
type(pdata6)Out[23]: pandas.core.panel.Panel
type(stacked)Out[24]: pandas.core.frame.DataFrame

第六章
6.1 读写文本格式的数据read_csvread_tableread_fwfread_clipboard

6.2 显示文件内容 type, cat, open
windows cmd:type ex1.csvlinux:!cat ex1.csvpython:open(r"data/ch06/ex1.csv").read()list(open('data/ch06/ex3.txt'))
Pandas工具:
pd.read_csv('data/ch06/ex1.csv')
names1 = ['a','b','c','d','message']df3=pd.read_csv('data/ch06/ex2.csv', names=names1, index_col='message')
6.3 read_csv/ read_table函数的参数

6.4 逐行读取文件
df10 = pd.read_csv('data/ch06/ex6.csv', nrows=5) #读取5行
chunker = pd.read_csv('data/ch06/ex6.csv', chunksize = 1000) #读取块,前1000行
tot = Series([ ])for piece in chunker:tot = tot.add(piece['key'].value_counts(), fill_value=0)#tot = tot.order(ascending = False)
输出结果:df10Out[16]: one two three four key0 0.467976 -0.038649 -0.295344 -1.824726 L1 -0.358893 1.404453 0.704965 -0.200638 B2 -0.501840 0.659254 -0.421691 -0.057688 G3 0.204886 1.074134 1.388361 -0.982404 R4 0.354628 -0.133116 0.283763 -0.837063 Q
tot.order(ascending = False)-c:1: FutureWarning: order is deprecated, use sort_values(...)Out[17]: E 368.0X 364.0L 346.0O 343.0Q 340.0M 338.0J 337.0F 335.0K 334.0...dtype: float64
chunkerOut[18]: <pandas.io.parsers.TextFileReader at 0xac8b3c8>

6.5 输出写到文件中:data.to_csv('data/ch06/out.csv')仅仅打印,而不用写到文件:data.to_csv(sys.stdout, sep='|')


6.6 Series 写入Series.to_csv, 读取Series.from_csv


6.7 csv文件的整理csv.Dialect 定义新格式
class my_dialect(csv.Dialect):lineterminator = '\n'delimiter = ';'quotechar = '"'
f=open('data/ch06/ex7.csv')
reader = csv.reader(f, dialect = my_dialect)

--------------------
使用python的csv生成excel所兼容的csv文件的话,主要就是创建writer时的参数时要有dialect=’excel’
(目前理解不了)

6.8 JSON数据:JavaScript Object Notation, 通过HTTP请求在Web浏览器和其他应用程序之间发送数据的标准格式之一
JSON转化为Python对象:dict = json.loads(JSON objection)

Python对象转化为JSON:
str = json.dumps(result)

6.9 XML 和 HTML: Web信息收集 P174~179
网络爬虫:http://blog.csdn.net/column/details/why-bug.htmlhttp://www.cnblogs.com/xin-xin/p/4297852.html
看下这个,用requests写的,比urllib代码简单点。其次就是正则表达式,匹配到自己想要抓取的内容http://blog.csdn.net/tangdou5682/article/details/52596863



示例:# -*- coding: utf-8 -*-import pandas as pd; import numpy as np; import pylab as plimport urllib2from pandas import Series
from lxml.html import parsefrom urllib2 import urlopen
from pandas import ExcelFile
parsed = parse(urlopen('http://finance.yahoo.com/quote/AAPL/history?p=AAPL'))#parsed type is lxml.etree._ElementTree
doc = parsed.getroot()#doc type is lxml.html.HtmlElement
links = doc.findall('.//a')#links type is list, html中链接是a标签,使用findall('.//a')得到文档中的所有URL链接
lnk = links[2]
'''lnk.get('href')#list.get('href')是提取URL链接格式的方法Out[38]: 'https://www.flickr.com/'
lnk.text_content() #list.text_content()是针对显示文本的提取方法Out[39]: 'Flickr''''
urls = [lnk.get('href') for lnk in doc.findall('.//a')]#获取doc中的所有URL
tables = doc.findall('.//table')#获取doc中的表格, tables type is list,元素为HtmlElementcalls=tables[0]#calls type is lxml.html.HtmlElement
rows = calls.findall('.//tr')#获取call中的tr(数据行)??, rows type is list, 元素为tr
def _unpack(row, kind='td'):#函数对象为tr数据行,获取数据行单元格内文件,标题行 kind='th';数据行 kind='td'elts = row.findall('.//%s' % kind)return [val.text_content() for val in elts]#返回值为list类型
#_unpack(rows[0], kind='td')
from pandas.io.parsers import TextParser#所有步骤合在一起,将数据转换为一个DataFrame
def parse_options_data(table):rows = table.findall('.//tr') #由tr组成的listheader = _unpack(rows[0], kind='th')data = [_unpack(r) for r in rows[1:]]return TextParser(data, names=header).get_chunk()#pandas中的TextParser类,将可以将字符串转化为数字的数据转化为浮点数格式,同样适用于read_csv等
call_data = parse_options_data(calls)call_data[:10]
6.9.5 findall()
findAll(name,attrs,recursive,text,limit,**kwargs)
html链接是a标签: links = doc.findall('.//a')

re.search和re.findall的区别和联系:
函数返回结果 常见的获得对应的值的方法 常见疑问及解答
re.search 一个Match对象 通过Match对象内的group编号或命名,获得对应的值 问:为何search只匹配到一项,而不是所有匹配的项?
答:因为search本身的功能就是:
从左到右,去计算是否匹配,如果有匹配,就返回。
即只要找到匹配,就返回了。
所以,最多只会匹配一个,
而不会匹配多个。
想要匹配多个,请去使用re.findall
re.findall 一个列表;
列表中每个元素的值的类型,取决于你的正则表达式的写法
是元组tuple:当你的正则表达式中有(带捕获的)分组(简单可理解为有括号)
而tuple的值,是各个group的值所组合出来的
是字符串:当你的正则表达式中没有捕获的组(不分组,或非捕获分组)
字符串的值,是你的正则表达式所匹配到的单个完整的字符串
直接获得对应的列表
每个列表中的值,一般就是你想要的值了
参见下面的详细解释,需要注意四种不同类型的正则表达式的效果的区别。

6.10 利用lxml.objectify解析XML
示例:from lxml import objectifyfrom pandas import DataFrame

path = 'data/ch06/Performance_XML_Data/Performance_MNR.xml'parsed = objectify.parse(open(path)) #lxml.etree._ElementTreeroot = parsed.getroot() #lxml.objectify.ObjectifiedElement
data = []
skip_fields = ['PARENT_SEQ', 'INDICATOR_SEQ','DESIRED_CHANGE', 'DECIMAL_PLACES']
for elt in root.INDICATOR:#root.INDICATOR返回一个用于产生<INDICATOR>XML元素的生成器, type of elt is lxml.objectify.ObjectifiedElementel_data = {}for child in elt.getchildren(): #type of child is lxml.objectify.StringElementif child.tag in skip_fields: #type of child.tag is str, 相当于数据的行名continue #如continue,则直接跳到了下一个循环el_data[child.tag] = child.pyval #child.pyval是每行的数据,类型在本例中为str,float,unicodedata.append(el_data)
#data的具体数据分层格式为 [{tag1: value1, tag2: value2,...},{},...]
perf = DataFrame(data)


原始.xml内容形式:INDICATOR是数据中的最外围分隔符两个INDICATOR之间的内容就是 elt的形式, elt type is lxml.objectify.ObjectifiedElement
child = elt.getchildren()#type of child is lxml.objectify.StringElement将elt中的具体内容提取出来,包括child.tag和child.pyval两部分
child.tag 类型如下:
AGENCY_NAMEINDICATOR_NAMEDESCRIPTIONPERIOD_YEARPERIOD_MONTHCATEGORYFREQUENCYDESIRED_CHANGEINDICATOR_UNITDECIMAL_PLACESYTD_TARGETYTD_ACTUALMONTHLY_TARGETMONTHLY_ACTUAL
child.pyval数据内容的形式如下:
Metro-North RailroadEscalator AvailabilityPercent of the time that escalators are operational systemwide. The availability rate is based on physical observations performed the morning of regular business days only. This is a new indicator the agency began reporting in 2009.201012Service IndicatorsMU%197.096.8497.090.03373889


将child转化为DataFrame的perf,内容如下:
perf[:1].stack()
Out[63]: 0 AGENCY_NAME Metro-North RailroadCATEGORYService IndicatorsDESCRIPTIONPercent of commuter trains that arrive at thei...FREQUENCYMINDICATOR_NAME On-Time Performance (West of Hudson)INDICATOR_UNIT %MONTHLY_ACTUAL96.9MONTHLY_TARGET95PERIOD_MONTH1PERIOD_YEAR 2008YTD_ACTUAL96.9YTD_TARGET 95
6.11 二进制数据格式
pickle:序列化二进制数据,用于短期储存,难以稳定
HDF5格式:处理1GB以上数据,速度优势,适合一次写,多次读
import pandas as pd; import numpy as np; import pylab as pl
frame = pd.read_csv('data/ch06/ex1.csv')#frame of df is DataFrame
frame.to_pickle('data/ch06/frame_pickle')#将DataFrame保存为pickle格式,
df = pd.read_pickle('data/ch06/frame_pickle')#type of df is DataFrame

store = pd.HDFStore('mydata.h5')#type of store is pandas.io.pytables.HDFStore, 并将store存为mydata.h5文件# .h5文件有点类似于字典
store['obj1'] = frame # type of frame is pandas.core.frame.DataFramestore['obj1_col'] = frame['a'] #type of frame['a'] is pandas.core.series.Series

6.12 读取Excel文件
xls_file = pd.ExcelFile('data/ch06/data.xlsx')#导入Excel文件,type of xls_file is pandas.io.excel.ExcelFiletable = xls_file.parse('Sheet1')#存放在Sheet1工作表中的数据可以通过parse读取到DataFrame中
6.13 使用HTML和Web API
API定义:API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。
import requestsurl = 'https://api.github.com/repos/pydata/pandas/milestones/28/labels'resp = requests.get(url) # type of resp is requests.models.Response
import jsondata = json.loads(resp.text)#使用json将url的Response转化为list#data的数据结构: [{key1:v1,key2:v2,...},{ ..}]
key = data[0].keys()
issue_labels = DataFrame(data)#将data的从list格式转变为DataFrame,每个dict变为一行
6.14 数据库
importsqlite3
打开数据库:cx=sqlite3.connect("E:/test.db")创建数据库在内存中:con=sqlite3.connect(":memory:")
数据库连接对象 打开数据库时返回的对象cx就是一个数据库连接对象,它可以有以下操作:
  1. commit()--事务提交
  2. rollback()--事务回滚
  3. close()--关闭一个数据库连接
  4. cursor()--创建一个游标
关于commit(),如果isolation_level隔离级别默认,那么每次对数据库的操作,都需要使用该命令,你也可以设置isolation_level=None,这样就变为自动提交模式。
1. 建表cu.execute("createtablecatalog(idintegerprimarykey,pidinteger,namevarchar(10)UNIQUE,nicknametextNULL)")上面语句创建了一个叫catalog的表,它有一个主键id,一个pid,和一个name,name是不可以重复的,以及一个nickname默认为NULL。2. 插入数据错误写法:#Neverdothis--insecure会导致注入攻击pid=200c.execute("...wherepid='%s'"%pid)

正确的做法如果t只是单个数值,也要采用t=(n,)的形式,因为元组是不可变的。#fortin[(0,10,'abc','Yu'),(1,20,'cba','Xu')]:cx.execute("insertintocatalogvalues(?,?,?,?)",t)简单的插入两行数据,不过需要提醒的是,只有提交了之后,才能生效.我们使用数据库连接对象cx来进行提交commit和回滚rollback操作.cx.commit()3.查询cu.execute("select*fromcatalog")要提取查询到的数据,使用游标的fetch函数,如:In[10]:cu.fetchall()Out[10]:[(0,10,u'abc',u'Yu'),(1,20,u'cba',u'Xu')]如果我们使用cu.fetchone(),则首先返回列表中的第一项,再次使用,则返回第二项,依次下去.4.修改In[12]:cu.execute("updatecatalogsetname='Boy'whereid=0")In[13]:cx.commit()注意,修改数据以后提交5.删除cu.execute("deletefromcatalogwhereid=1")cx.commit()6.使用中文请先确定你的IDE或者系统默认编码是utf-8,并且在中文前加上ux=u'鱼'cu.execute("updatecatalogsetname=?whereid=0",x)cu.execute("select*fromcatalog")cu.fetchall()[(0,10,u'\u9c7c',u'Yu'),(1,20,u'cba',u'Xu')]如果要显示出中文字体,那需要依次打印出每个字符串In[26]:foritemincu.fetchall():....:forelementinitem:....:printelement,....:print....:010鱼Yu120cbaXu7.Row类型Row提供了基于索引和基于名字大小写敏感的方式来访问列而几乎没有内存开销。 原文如下:sqlite3.Rowprovides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.Row对象的详细介绍classsqlite3.RowARowinstance serves as a highly optimizedrow_factoryforConnectionobjects. It tries to mimic a tuple in most of its features.It supports mapping access by column name and index, iteration, representation, equality testing andlen().If twoRowobjects have exactly the same columns and their members are equal, they compare equal.Changed in version 2.6: Added iteration and equality (hashability).keys()This method returns a tuple of column names. Immediately after a query, it is the first member of each tuple inCursor.description.New in version 2.6. 下面举例说明In[30]:cx.row_factory=sqlite3.Row
In[31]:c=cx.cursor()
In[32]:c.execute('select*fromcatalog')Out[32]:<sqlite3.Cursorobjectat0x05666680>
In[33]:r=c.fetchone()
In[34]:type(r)Out[34]:<type'sqlite3.Row'>
In[35]:rOut[35]:<sqlite3.Rowobjectat0x05348980>
In[36]:printr(0,10,u'\u9c7c',u'Yu')
In[37]:len(r)Out[37]:4
In[39]:r[2] #使用索引查询Out[39]:u'\u9c7c'
In[41]:r.keys()Out[41]:['id','pid','name','nickname']
In[42]:foreinr:....:printe,....:010鱼Yu使用列的关键词查询In[43]:r['id']Out[43]:0
In[44]:r['name']Out[44]:u'\u9c7c'
6.14 数据库直接转化为 DataFrame
import pandas.io.sql as sql
sql1 = sql.read_sql('select * from test', con)#con type is sqlite3.Connection,con是之前存储在内存中的一个数据库文件
输出:a b c d0 Atlanta Georgia 1.25 61 Tallahhassee Florida 2.60 32 Sacramento California 1.70 5
6.15 存取MongoDB中的数据 --mongodb
http://www.cnblogs.com/bigbigtree/p/3242483.htmlhttp://blog.csdn.net/kwsy2008/article/details/48969607http://blog.csdn.net/u010035907/article/details/52908434
示例:import pymongoimport jsonimport requests
from pandas import DataFrame
url = 'https://api.github.com/repos/pydata/pandas/milestones/28/labels'resp = requests.get(url)# type of resp is requests.models.Responsedata = json.loads(resp.text)#使用json将url的Response转化为list#data的数据结构: [{key1:v1,key2:v2,...},{ ..}]
tweets = DataFrame(data)
con = pymongo.Connection('localhost',port=27017)#type of con is pymongo.connection.Connection,27017是MongoDB默认端口,http://localhost:27017/, pymongo通过该默认端口进行连接db_tweets = con.db.tweets#type of db_tweets is pymongo.collection.Collection,MongoDB的文档被组织在数据库的集合(collection)中,本例中,tweets作为DataFrame,其数据被保存进MongoDB数据库中,以db_tweets形式(connection)被调用和管理
for x in data:dict_x = dict(x)db_tweets.save(dict_x) #collection.save(dict)的形式进行保存

dict2 = {u'name': u'Bug'}cursor=db_tweets.find(dict2)#迭代器pymongo.cursor.Cursor,查找含有某一子字典的元素
key2=['color','id', 'name','url']
result = DataFrame(list(cursor), columns=key2)#查找cursor指向的元素,并保存key2指定的列
第七章 数据规整化:清理、转换、合并、重塑

7.1

7.2 索引上的合并
合并之后,原有DataFrame的index信息被舍弃了。
pd.merge(DF1, DF2, left_on='key', right_index=True)即将DF1中的 'key'这一列和DF2的index作为研究对象。如果值相同就合并列表
left1 = DataFrame({'key':['a','b','a','a','b','c'],'value':range(6)})right1 = DataFrame({'group_val':[3.5, 7]}, index = ['a','b'])
df8 = pd.merge(left1, right1, left_on = 'key',right_index = True, how='outer')
输出:left1Out[8]: key value0 a 01 b 12 a 23 a 34 b 45 c 5
right1Out[9]: group_vala 3.5b 7.0
df8Out[13]: key value group_val0 a 0 3.52 a 2 3.53 a 3 3.51 b 1 7.04 b 4 7.05 c 5 NaN
进一步层次化索引:
left2 = DataFrame([[1.,2.],[3.,4.],[5.,6.]], index=['a','c','e'],columns=['Ohio','Nevada'])right2 = DataFrame([[7.,8.],[9.,10.],[11.,12.],[13,14]], index=['b','c','d','e'],columns=['Missouri','Alabama'])
df10=pd.merge(left2, right2, how='outer',left_index=True, right_index=True)
输出:left2Out[22]: Ohio Nevadaa 1.0 2.0c 3.0 4.0e 5.0 6.0
right2Out[23]: Missouri Alabamab 7.0 8.0c 9.0 10.0d 11.0 12.0e 13.0 14.0
df10Out[25]: Ohio Nevada Missouri Alabamaa 1.0 2.0 NaN NaNb NaN NaN 7.0 8.0c 3.0 4.0 9.0 10.0d NaN NaN 11.0 12.0e 5.0 6.0 13.0 14.0
方法二: join
df11 = left2.join(right2, how='outer')df12 = left1.join(right1, on='key')
7.3 轴向链接numpy.concatenate([arr1, arr2], axis=1 or 0)pandas.concat([Series1, Series2, Series3], axis =0 or 1)#若为0,则仍为Series; 若为1,则变成DataFrame

result = pd.concat([s1,s1,s3], keys = ['one','two','three']) #result type is Seriesresult2 = pd.concat([s1,s1,s3], keys = ['one','two','three'],axis=1) #result2 type is DataFrame
df23 = pd.concat([df1,df2], axis=1, keys=['level1','level2'])#DataFrame相互合并
df24 = pd.concat({'level1':df1, 'level2':df2}, axis=1)#字典合并后转化为DataFrame,字典的key转化为DataFrame列头的key




7.4 合并重叠数据
numpy.where( 某条件,B, A)//A中的null元素,用B中对应的元素补上,其他则沿用ASeries_B.combine_first(Series_A) // #A和B合并,相同的元素用B,不同的部分,各自补上
A= Series([np.nan,2.5,np.nan, 3.5,4.5,np.nan], index=['f','e','d','a','b','c'])B= Series(np.arange(len(A)), dtype = np.float64, index=['f','e','d','a','b','c'])
df41=np.where(pd.isnull(A),B,A) #A中的null元素,用B中对应的元素补上,其他则沿用A
df42=B[:-2].combine_first(A[2:]) #A和B合并,相同的元素用B,不同的部分,各自补上
输出:
A[2:]Out[92]: d NaN #都有a 3.5 #都有b 4.5 #只有A有c NaN #只有A有dtype: float64
B[:-2]Out[93]: f 0.0e 1.0d 2.0a 3.0dtype: float64
df42Out[91]: a 3.0 #来自Bb 4.5 #来自Ac NaN #Ad 2.0 #Be 1.0 #Bf 0.0 #Bdtype: float64

7.5 重塑与轴向旋转
stack:将数据的列“旋转”为行unstack:将数据的行“旋转”为列
data = DataFrame(np.arange(6).reshape((2, 3)),index=pd.Index(['Ohio', 'Colorado'], name='state'),columns=pd.Index(['one', 'two', 'three'], name='number'))result3 = data.stack()
df51 = DataFrame({'left':result3, 'right':result3+5},columns=pd.Index(['left','right'], name='side'))df52 = df51.unstack('state')df53 = df51.unstack('state').stack('side')
输出:df51Out[114]: side left rightstate number Ohio one 0 5two 1 6three 2 7Colorado one 3 8two 4 9three 5 10
df52Out[115]: side left rightstate Ohio Colorado Ohio Coloradonumber one 0 3 5 8two 1 4 6 9three 2 5 7 10
df53Out[116]: state Ohio Coloradonumber side one left 0 3right 5 8two left 1 4right 6 9three left 2 5right 7 10
7.6 将“长格式”旋转为 “宽格式” --将SQL常用的csv格式:列名和数据类型,转化为DataFrame
工具:“长格式”旋转为 “宽格式”:若value只有一个类型DataFrame.pivot('column1', 'column2', 'value')//column1为行名,column2为列名若value有两列以上DataFrame.pivot('column1', 'column2')
“宽格式”旋转为 “长格式”ldata = data.stack().reset_index().rename(columns={0: 'value'})
例:data = pd.read_csv('data/ch07/macrodata.csv')
periods = pd.PeriodIndex(year=data.year, quarter=data.quarter, name='date')data1 = DataFrame(data.to_records(),columns=pd.Index(['realgdp', 'infl', 'unemp'], name='item'),index=periods.to_timestamp('D', 'end'))
ldata = data1.stack().reset_index().rename(columns={0: 'value'})wdata = ldata.pivot('date', 'item', 'value')
ldata['value2']=np.random.randn(len(ldata))
pivoted = ldata.pivot('date','item')
输出:
data = pd.read_csv('data/ch07/macrodata.csv') //读取文件为DataFrame
data
year quarter realgdp realcons realinv realgovt realdpi cpi m1 tbilrate unemp pop infl realint
1959 1 2710.349 1707.4 286.898 470.045 1886.9 28.98 139.7 2.82 5.8 177.146 0 0
1959 2 2778.801 1733.7 310.859 481.301 1919.7 29.15 141.7 3.08 5.1 177.83 2.34 0.74

... ...
periods = pd.PeriodIndex(year=data.year, quarter=data.quarter, name='date')//截取data部分数据,新建 pandas.tseries.period.PeriodIndex,并命名为dateperiodsPeriodIndex(['1959Q1', '1959Q2', '1959Q3', '1959Q4', '1960Q1', '1960Q2','1960Q3', '1960Q4', '1961Q1', '1961Q2',...'2007Q2', '2007Q3', '2007Q4', '2008Q1', '2008Q2', '2008Q3','2008Q4', '2009Q1', '2009Q2', '2009Q3'],dtype='int64', name=u'date', length=203, freq='Q-DEC')
data1 = DataFrame(data.to_records(),columns=pd.Index(['realgdp', 'infl', 'unemp'], name='item'),index=periods.to_timestamp('D', 'end'))//对于data数据重新排序,列取列名为'realgdp', 'infl', 'unemp'的三列;行用periods来表征// periods.to_timestamp('D', 'end')),将periods的数据由 季度格式 转为日期形式,data1item realgdp infl unempdate 1959-03-31 2710.349 0.00 5.81959-06-30 2778.801 2.34 5.1... ...
periods.to_timestamp('D','end')Out[160]: DatetimeIndex(['1959-03-31', '1959-06-30', '1959-09-30', '1959-12-31','1960-03-31', '1960-06-30', '1960-09-30', '1960-12-31','1961-03-31', '1961-06-30',...'2007-06-30', '2007-09-30', '2007-12-31', '2008-03-31','2008-06-30', '2008-09-30', '2008-12-31', '2009-03-31','2009-06-30', '2009-09-30'],dtype='datetime64[ns]', name=u'date', length=203, freq='Q-DEC')
ldata = data1.stack().reset_index().rename(columns={0: 'value'})data1.stack() //DataFrame.stack() 列“旋转”为行Out[152]: date item 1959-03-31 realgdp 2710.349infl 0.000unemp 5.8001959-06-30 realgdp 2778.801infl 2.340unemp 5.100
data1.stack().reset_index()// .reset_index() 将列名和行名补充完整Out[153]: date item 00 1959-03-31 realgdp 2710.3491 1959-03-31 infl 0.000
data1.stack().reset_index().rename(columns={0: 'value'})//.rename() 将列名重新命名Out[154]: date item value0 1959-03-31 realgdp 2710.3491 1959-03-31 infl 0.000
wdata = ldata.pivot('date', 'item', 'value') //“长格式”旋转为 “宽格式”
wdataOut[155]: item infl realgdp unempdate 1959-03-31 0.00 2710.349 5.81959-06-30 2.34 2778.801 5.1

ldata['value2']=np.random.randn(len(ldata)) //新建 value2 一列
ldataOut[156]: date item value value20 1959-03-31 realgdp 2710.349 2.9511471 1959-03-31 infl 0.000 -0.146163
pivoted = ldata.pivot('date','item') //“长格式”旋转为 “宽格式”
pivotedOut[157]: value value2 item infl realgdp unemp infl realgdp unempdate 1959-03-31 0.00 2710.349 5.8 -0.146163 2.951147 0.5361291959-06-30 2.34 2778.801 5.1 0.640442 1.903347 -0.313551

7.7 移除重复数据
data.duplicated()//返回一个布尔型Seriesdata.drop_duplicates(['k1'])//依据k1列过滤重复项data.drop_duplicates(['k1', 'k2'], take_last=True)//duplicated 和 drop_duplicates 默认保留第一个出现的值组合,传人take_last=True则保留最后一个。
7.8 利用函数或映射进行数据转换
data['animal'] = data['food'].map(str.lower).map(meat_to_animal)
data 为DataFrame类型meat_to_animal为字典类型#map(str.lower)将所有字母都转化为小写,map(meat_to_animal)映射
7.9 替换
data.replace([-999, -1000], [np.nan, 0])

data.replace({-999: np.nan, -1000: 0})
7.10 重命名轴索引
data = DataFrame(np.arange(12).reshape((3, 4)),index=['Ohio', 'Colorado', 'New York'],columns=['one', 'two', 'three', 'four'])
data.rename(index={'OHIO': 'INDIANA'}, columns={'three': 'peekaboo'})
如果想就地修改索引轴的名称:传入 inplace = True
_ = data.rename(index={'OHIO': 'INDIANA'}, inplace=True)

7.11 离散化 和 面元划分
ages = [20, 22, 25, 27, 21, 23, 37, 31, 61, 45, 41, 32]bins = [18, 25, 35, 60, 100]cats = pd.cut(ages, bins)//按区间bins,将ages划分开
group_names = ['Youth', 'YoungAdult', 'MiddleAged', 'Senior']pd.cut(ages, bins, labels=group_names)//区间的改名
data = np.random.rand(20)pd.cut(data, 4, precision=2)//将data划分为4个同等宽度的区间
cats = pd.qcut(data, 4) # Cut into quartiles//将data划分为1/4位,中位数,3/4位的四个区间,每个区间元素数量相同。

cats.labels //排位第x个区间
Out[14]: array([1, 2, 0, 3, 1, 2, 3, 2, 2, 0, 3, 3, 1, 0, 2, 0, 0, 1, 3, 1], dtype=int8)
cats.levels //每个数排的区间为-c:1: FutureWarning: Accessing 'levels' is deprecated, use 'categories'Out[15]: Index([u'[0.0249, 0.15]', u'(0.15, 0.507]', u'(0.507, 0.72]',u'(0.72, 0.995]'],dtype='object')
pd.value_counts(cats)//每个区间的数量Out[16]: (0.72, 0.995] 5(0.507, 0.72] 5(0.15, 0.507] 5[0.0249, 0.15] 5dtype: int64
7.12 检测和过滤异常值
col1 = col[np.abs(col)>3] #Series选择和转化data1 = data[(np.abs(data)>3).any(1)] #DataFrame选择和转化,每行只要1个元素满足条件np.abs(data)>3即可 .any(1)
data[np.abs(data)>3] = np.sign(data)*3 #.sign(data)元素转换为 1或-1
7.13 排列和随机采样
对于Series和DataFrame排序:numpy.random.permutation // 随机重排序
df = DataFrame(np.arange(5 * 4).reshape((5, 4)))sampler = np.random.permutation(5)// 产生5个一组的随机数
df2 = df.take(sampler)//将df中的行顺序换为sampler中的顺序
np.random.randint(-20, 100, size=10)//在-20和100之间,随机取10个数,组成一个array
7.14 计算指标 、哑变量
将Series转化为DataFrame: pandas.get_dummies(Series)
df = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'], 'data1': [11,12,13,14,15,16]})df2=pd.get_dummies(df['key'])
输出:df['key'] //Series类型Out[75]: 0 b1 b2 a3 c4 a5 bName: key, dtype: object
df2 //DataFrame类型Out[74]: a b c0 0.0 1.0 0.01 0.0 1.0 0.02 1.0 0.0 0.03 0.0 0.0 1.04 1.0 0.0 0.05 0.0 1.0 0.0
在DataFrame前面加前缀:pandas.get_dummies(Series, prefix = 'words')DataFrame = DataFrame1.join(DataFrame2)// 在DataFrame1后面加上DataFrame2,合并DataFrame
dummies = pd.get_dummies(df['key'], prefix='key')//在行名的前面加上 key_, 又a变为key_adf_with_dummy = df[['data1']].join(dummies) //加上
输出:dummiesOut[80]: key_a key_b key_c0 0.0 1.0 0.01 0.0 1.0 0.02 1.0 0.0 0.03 0.0 0.0 1.04 1.0 0.0 0.05 0.0 1.0 0.0
df_with_dummyOut[81]: data1 key_a key_b key_c0 11 0.0 1.0 0.01 12 0.0 1.0 0.02 13 1.0 0.0 0.03 14 0.0 0.0 1.04 15 1.0 0.0 0.05 16 0.0 1.0 0.0
//对于复杂的数据,将某一列复杂的数据具体分析,将数据拆开,变为列名
mnames = ['movie_id', 'title', 'genres']movies = pd.read_table('data/ch02/movielens/movies.dat', sep='::', header=None,names=mnames)//pandas.read_table('x.dat') 读取 .dat文件,分隔符为::,行名没有,列名用mnames命名
genre_iter = (set(x.split('|')) for x in movies.genres)#type is genetatorgenres = sorted(set.union(*genre_iter))#type is list, genetator 转化为 genre_iter
dummies = DataFrame(np.zeros((len(movies), len(genres))), columns=genres)
for i, gen in enumerate(movies.genres):dummies.ix[i, gen.split('|')] = 1# i=1, gen='Drama|Thriller'# gen.split('|')=['Drama', 'Thriller'] '''dummies.ix[1]Out[15]:Action 0.0Adventure 1.0Animation 0.0Children's 1.0Comedy 0.0Crime 0.0Documentary 0.0Drama 0.0Fantasy 1.0Film-Noir 0.0Horror 0.0Musical 0.0Mystery 0.0Romance 0.0Sci-Fi 0.0Thriller 0.0War 0.0Western 0.0Name: 1, dtype: float64
dummies.ix[1,gen.split('|')]#赋值为1之后,Drama和Thriller都变为1Out[14]:Drama 0.0Thriller 0.0Name: 1, dtype: float64
'''
movies_windic = movies.join(dummies.add_prefix('Genre_'))#在dummies的列头之前加‘Genew_’,并将dummies与movies合并movies_windic.ix[0]


7.15 Set -- 生产uniqe元素的列表
t=set("Hello")#创建一个唯一字符的集合
>>>tset(['H','e','l','o'])
7.16 字符串操作
str.split('x') 将str转化为liststr.strip('x') 移除头尾字符'x'
val1 = val.split(',')pieces = [x.strip() for x in val.split(',')]
str.strip([chars])
示例2str="0000000this is string example....wow!!!0000000";print str.strip('0');输出:thisisstring example....wow!!!

--------------
Python中字符串str有个内建方法split()用于分割字符串,返回一个分割后的列表。这在处理数据中非常方便好用。#将string转化为list废话不多说,直接上代码:>>> aStr ='data1 | data2 | data3 | data4 | data5'>>> aList = aStr.split(' | ')>>> aList['data1','data2','data3','data4','data5']

描述Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串语法split()方法语法:str.split(str="", num=string.count(str)).参数
  • str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • num -- 分割次数。
返回值返回分割后的字符串列表。实例以下实例展示了split()函数的使用方法:#!/usr/bin/pythonstr="Line1-abcdef \nLine2-abc \nLine4-abcd";print str.split();print str.split(' ',1);以上实例输出结果如下:['Line1-abcdef','Line2-abc','Line4-abcd']['Line1-abcdef','\nLine2-abc \nLine4-abcd']
7.17 正则表达式 (regex)
import retext = "foo bar\t baz \tqux"re.split('\s+', text)# \s+ 描述一个或多个空白符输出:Out[7]: ['foo', 'bar', 'baz', 'qux']
regex=re.compile('\s+')#type of regex is _sre.SRE_Pattern
regex.split(text)输出:Out[8]: ['foo', 'bar', 'baz', 'qux']
表面看上去, re.split('\s+',text)和re.compile('\s+').split(text)输出结果一样,但实际上,complie编译方法,在多个字符串处理的时候,速度更快,节省大量CPU时间
强烈建议 编译 compile
示例:
import pandas as pd;import re
text0 = "foo bar\t baz \tqux"re.split('\s+', text0) # \s+ 描述一个或多个空白符
regex0=re.compile('\s+')#type of regex is _sre.SRE_Patternregex.split(text)#输出为['foo', 'bar', 'baz', 'qux']regex.findall(text) #输出为[' ', '\t ', ' \t']

text = """Dave dave@google.comSteve steve@gmail.comRob rob@gmail.comRyan ryan@yahoo.com"""pattern = r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'
# re.IGNORECASE makes the regex case-insensitive, 忽视大小写regex = re.compile(pattern, flags=re.IGNORECASE)
m = regex.search(text)
print regex.match(text) #会报错,因为match只适用于纯字符串,不包含空格、空行等
pattern2 = r'([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})'regex2 = re.compile(pattern2, flags=re.IGNORECASE)
m2 = regex2.match('wesm@bright.net')#type of m2 is _sre.SRE_Match, match 适应于字符串格式,返回一个元组m2_1 = regex2.match(text)#match不适用,会报错
m2.groups #m.groups() 返回所有括号匹配的字符,以tuple格式。
regex2.findall('wesm@bright.net')#返回一个list,只包含一个元素,元素为元组regex2.findall(text)#返回一个list,只包含4个元素,元素为元组
print(regex2.sub(r'Username: \1, Domain: \2, Suffix: \3', text))# .sub() 将匹配到的模式替换为指定字符串'''#输出为Dave Username: dave, Domain: google, Suffix: comSteve Username: steve, Domain: gmail, Suffix: comRob Username: rob, Domain: gmail, Suffix: comRyan Username: ryan, Domain: yahoo, Suffix: com'''
regex3 = re.compile(r"""(?P<username>[A-Z0-9._%+-]+)@(?P<domain>[A-Z0-9.-]+)\.(?P<suffix>[A-Z]{2,4})""", flags=re.IGNORECASE|re.VERBOSE)
m3 = regex3.match('wesm@bright.net')
m3.groupdict() #可以用正则式,将email转化为字典#输出为:{'domain': 'bright', 'suffix': 'net', 'username': 'wesm'}
m3.groups()#Out[50]: ('wesm', 'bright', 'net')
7.18 pandas中矢量化的字符串函数
Series.str.contains('key words')data.str.contains('gmail')
Series.str.match(parttern, flags=re.IGNORECASE or other)matches = data.str.match(pattern, flags=re.IGNORECASE)data.str.findall(pattern, flags=re.IGNORECASE)
Series.str.get(1) #获取元素Series.str[0] #获取元素
matches.str.get(1)输出:Dave google
matches.str[0]matches.str[1]输出:Dave daveDave google
7.19 USDA食品数据库 P225
关于Groupby()的内容和结构,容易糊涂,注意把握,实在掌握不了就来复习这个例子
7.20 pandas.concat( list, ), DataFrame1.append(DF2)
将list中的元素DataFrame,按照行名称和列名称进行整合,形成一个完整的新 DataFrame
http://pandas.pydata.org/pandas-docs/stable/merging.html
pandas.concat(objs,axis=0,join='outer',join_axes=None,ignore_index=False,keys=None,levels=None,names=None,verify_integrity=False,copy=True)
示例:
In [1]:df1= pd.DataFrame({'A': ['A0','A1','A2','A3'], ...:'B': ['B0','B1','B2','B3'], ...:'C': ['C0','C1','C2','C3'], ...:'D': ['D0','D1','D2','D3']}, ...: index=[0,1,2,3]) ...:In [2]:df2= pd.DataFrame({'A': ['A4','A5','A6','A7'], ...:'B': ['B4','B5','B6','B7'], ...:'C': ['C4','C5','C6','C7'], ...:'D': ['D4','D5','D6','D7']}, ...: index=[4,5,6,7]) ...:In [3]:df3= pd.DataFrame({'A': ['A8','A9','A10','A11'], ...:'B': ['B8','B9','B10','B11'], ...:'C': ['C8','C9','C10','C11'], ...:'D': ['D8','D9','D10','D11']}, ...: index=[8,9,10,11]) ...:In [4]:frames= [df1, df2, df3]In [5]: result= pd.concat(frames)
In [6]:result= pd.concat(frames, keys=['x','y','z'])In [7]:result.ix['y']Out[7]:A B C D4 A4 B4 C4 D45 A5 B5 C5 D56 A6 B6 C6 D67 A7 B7 C7 D7
In [8]:df4= pd.DataFrame({'B': ['B2','B3','B6','B7'], ...:'D': ['D2','D3','D6','D7'], ...:'F': ['F2','F3','F6','F7']}, ...: index=[2,3,6,7]) ...:In [9]:result= pd.concat([df1, df4], axis=1) #指明合并的轴和方向
In [15]:result= pd.concat([df1, df4], ignore_index=True)#用ignore_index的方法,来处理哪些列名称相同的部分,列名称不同的部分用NaN来处理,有点模糊查找、匹配的意思示例2:DataFrame1.append(DataFrame2)
In [12]:result= df1.append(df2)

In [13]:result= df1.append(df4)
第八章 绘图和可视化
8.1 numpy.cumsum()
numpy.cumsum(a,axis=None,dtype=None,out=None)[source]Return the cumulative sum of the elements along a given axis.
Parameters: a : array_like
Input array.
axis : int, optional
Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. Seedoc.ufuncs (Section “Output arguments”) for more details.
Returns: cumsum_along_axis : ndarray.
A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

>>>a= np.array([[1,2,3], [4,5,6]])>>>aarray([[1, 2, 3], [4, 5, 6]])>>>np.cumsum(a)array([ 1, 3, 6, 10, 15, 21])>>>np.cumsum(a, dtype=float)# specifies type of output value(s)array([ 1., 3., 6., 10., 15., 21.])>>>>>>np.cumsum(a,axis=0)# sum over rows for each of the 3 columnsarray([[1, 2, 3], [5, 7, 9]])>>>np.cumsum(a,axis=1)# sum over columns for each of the 2 rowsarray([[ 1, 3, 6], [ 4, 9, 15]])
8.2 pythonlist中append()与extend()用法
列表是以类的形式实现的。“创建”列表实际上是将一个类实例化。因此,列表有多种方法可以操作。1. 列表可包含任何数据类型的元素,单个列表中的元素无须全为同一类型。2. append() 方法向列表的尾部添加一个新的元素。只接受一个参数。3. extend()方法只接受一个列表作为参数,并将该参数的每个元素都添加到原有的列表中。**********************************************************************************************************************append()用法示例:>>> mylist = [1,2,0,'abc']>>> mylist[1, 2, 0, 'abc']>>> mylist.append(4)>>> mylist[1, 2, 0, 'abc', 4]>>> mylist.append('haha')>>> mylist[1, 2, 0, 'abc', 4, 'haha']>>>**********************************************************************************************************************extend()用法示例:>>> mylist[1, 2, 0, 'abc', 4, 'haha']>>> mylist.extend(['lulu'])>>> mylist[1, 2, 0, 'abc', 4, 'haha', 'lulu']>>> mylist.extend([aaa,'lalalala'])Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'aaa' is not defined>>> mylist.extend(['123123','lalalala'])>>> mylist[1, 2, 0, 'abc', 4, 'haha', 'lulu', '123123', 'lalalala']>>> mylist.extend([111111,222])>>> mylist[1, 2, 0, 'abc', 4, 'haha', 'lulu', '123123', 'lalalala', 111111, 222]>>>

示例2:a=[1,2,3]b=[4,5,6]a.append(b)
aOut[22]: [1, 2, 3, [4, 5, 6]]
a=[1,2,3]a.extend(b)
aOut[25]: [1, 2, 3, 4, 5, 6]

8.3 fig.add_subplot(x,y,z)

import matplotlib.pyplot as pltfrom numpy import *fig = plt.figure()ax = fig.add_subplot(349)ax.plot(x,y)plt.show()参数349的意思是:将画布分割成3行4列,图像画在从左到右从上到下的第9块,如下图:
那第十块怎么办,3410是不行的,可以用另一种方式(3,4,10)。如果一块画布中要显示多个图怎么处理?毛老师给出了另一种画法:import matplotlib.pyplot as pltfrom numpy import *fig = plt.figure()ax = fig.add_subplot(2,1,1)ax.plot(x,y)ax = fig.add_subplot(2,2,3)ax.plot(x,y)plt.show()
8.4pandas.Series.asof
Series.asof(where,subset=None)[source]
示例:time ticker bid ask0 2016-05-25 13:30:00.023 GOOG 720.50 720.931 2016-05-25 13:30:00.023 MSFT 51.95 51.962 2016-05-25 13:30:00.030 MSFT 51.97 51.983 2016-05-25 13:30:00.041 MSFT 51.99 52.004 2016-05-25 13:30:00.048 GOOG 720.50 720.935 2016-05-25 13:30:00.049 AAPL 97.99 98.016 2016-05-25 13:30:00.072 GOOG 720.50 720.887 2016-05-25 13:30:00.075 MSFT 52.01 52.03>>>trades time ticker price quantity0 2016-05-25 13:30:00.023 MSFT 51.95 751 2016-05-25 13:30:00.038 MSFT 51.95 1552 2016-05-25 13:30:00.048 GOOG 720.77 1003 2016-05-25 13:30:00.048 GOOG 720.92 1004 2016-05-25 13:30:00.048 AAPL 98.00 100By default we are taking the asof of the quotes>>>pd.merge_asof(trades, quotes,...on='time',...by='ticker')#保持trades的time和ticker顺序,将trades中没有的列加进来 time ticker price quantity bid ask0 2016-05-25 13:30:00.023 MSFT 51.95 75 51.95 51.961 2016-05-25 13:30:00.038 MSFT 51.95 155 51.97 51.982 2016-05-25 13:30:00.048 GOOG 720.77 100 720.50 720.933 2016-05-25 13:30:00.048 GOOG 720.92 100 720.50 720.934 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN
8.5matplotlib.pyplot.Rectabgle( (x,y), m, n, color = ' ',alpha = )
rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3) #aplpha 反应颜色的深浅程度
8.6 如何显示图片
plt.figure() 显示基本图片然后输入tips['tip_pct'].hist(bins=50),tips['tip_pct'].plot(kind='kde')这些图像的命令,即可显示出来
plt.close() 关闭图片
8.7 Series.hist(bins = , normed = True) 直方图# bins指的是 数据细分的程度,也反应直方图中每块方的宽度,数字越大,分的越细,宽度越小
values.hist(bins=50, alpha=0.3, color='k', normed=True)
values.hist(bins=50, alpha=0.3, color='k', normed=True)values.hist(bins=1000, alpha=0.3, color='k', normed=True)8.8 DataFrame. diff()是将DataFrame中的数据沿着某个方向移动之后,与原始数据比较求差值。
import pandas as pd; import numpy as npfrom pandas import DataFrame, Series
l1=['A','B','C','D']l2=[1,2,5,9]l3=[11,20,50,90]l4=['X','Y']
s1 = np.array([l2,l3])df = pd.DataFrame(s1.T,index=l1)
df.diff() #即 df.diff(periods=1, axis=0)#沿着纵向,向下平移得到矩阵DF_X,拿DF_X减去df
DF_XA NA NAB 1 11C 2 20D 5 50
df.diff() = DF_X - df
df.diff(periods=2, axis=0)
df2 = pd.DataFrame(s1,columns=l1)
df2.diff(periods=2, axis=1)
输出:dfOut[62]: 0 1A 1 11B 2 20C 5 50D 9 90

df.diff()Out[64]: 0 1A NaN NaNB 1.0 9.0C 3.0 30.0D 4.0 40.0
df.diff(periods=2, axis=0)Out[66]: 0 1A NaN NaNB NaN NaNC 4.0 39.0D 7.0 70.0
df2Out[73]: A B C D0 1 2 5 91 11 20 50 90
df2.diff(periods=2, axis=1)Out[74]: A B C D0 NaN NaN 4.0 7.01 NaN NaN 39.0 70.0
8.9 DataFrame.describe()
DataFrame.describe(percentiles=None,include=None,exclude=None)[source]Generate various summary statistics, excluding NaN values.
8.10 str.split( )
str.split(str="", num=string.count(str)).
参数
  • str -- 分隔符,默认为空格。
  • num -- 分割次数。
返回值返回分割后的字符串列表。实例以下实例展示了split()函数的使用方法:#!/usr/bin/pythonstr="Line1-abcdef \nLine2-abc \nLine4-abcd";print str.split();print str.split(' ',1);以上实例输出结果如下:['Line1-abcdef','Line2-abc','Line4-abcd']['Line1-abcdef','\nLine2-abc \nLine4-abcd']
8.11 str.strip([chars]) 移除头尾字符
描述Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。语法strip()方法语法:str.strip([chars]);参数
  • chars -- 移除字符串头尾指定的字符。
返回值返回移除字符串头尾指定的字符生成的新字符串。实例以下实例展示了strip()函数的使用方法:#!/usr/bin/pythonstr="0000000this is string example....wow!!!0000000";print str.strip('0');以上实例输出结果如下:thisisstring example....wow!!!8.12 set.union()
  1. set1=set([1,2])
  2. >>>set2=set([2,3])
  3. #合集
  4. #s.union(t)
  5. #s|t
  6. #返回一个新的set包含s和t中的每一个元素
  7. >>>set1.union(set2)
  8. set([1,2,3])

set.union(*generator)
def get_all_categories(cat_series):cat_sets = (set(to_cat_list(x)) for x in cat_series) #type is generatorreturn sorted(set.union(*cat_sets))
8.13 numpy.unique()
numpy.uniquenumpy.unique(ar,return_index=False,return_inverse=False,return_counts=False)[source]Find the unique elements of an array.
>>>np.unique([1,1,2,2,3,3])array([1, 2, 3])>>>a= np.array([[1,1], [2,3]])>>>np.unique(a)array([1, 2, 3])Return the indices of the original array that give the unique values:>>>>>>a= np.array(['a','b','b','c','a'])>>>u, indices= np.unique(a, return_index=True)>>>uarray(['a', 'b', 'c'], dtype='|S1')>>>indicesarray([0, 1, 3])>>>a[indices]array(['a', 'b', 'c'], dtype='|S1')Reconstruct the input array from the unique values:>>>>>>a= np.array([1,2,6,4,2,3,2])>>>u, indices= np.unique(a, return_inverse=True)>>>uarray([1, 2, 3, 4, 6])>>>indicesarray([0, 1, 4, 3, 1, 2, 1])>>>u[indices]array([1, 2, 6, 4, 2, 3, 2])
8.14 axes.flat
flat 是数组或图片组的 迭代器
然而,如果一个人想对每个数组中元素进行运算,我们可以使用flat属性,该属性是数组元素的一个迭代器:>>> for element in b.flat:... print element,...0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43
8.15 Basemap库的安装与使用
http://blog.sina.com.cn/s/blog_6ab074c30102w1an.html

第九章
9.1 groupby操作之后,产生一对成分,类似于dict中的key和value
df = DataFrame({'key1' : ['a', 'a', 'b', 'b', 'a'],'key2' : ['one', 'two', 'one', 'two', 'one'],'data1' : np.random.randn(5),'data2' : np.random.randn(5)})
for name, group in df.groupby('key1'):print(name)print(group)
输出:adata1 data2 key1 key20 -0.204708 1.393406 a one1 0.478943 0.092908 a two4 1.965781 1.246435 a onebdata1 data2 key1 key22 -0.519439 0.281746 b one3 -0.555730 0.769023 b two
9.2 DataFrame 转化为 dict -->dict(list(df.groupby('key')))
pieces = dict(list(df.groupby('key1')))#dict的key对应'key1'中出现的元素,value对应一个DataFrame矩阵
pieces['a']Out[57]: data1 data2 key1 key20 -0.204708 1.393406 a one1 0.478943 0.092908 a two4 1.965781 1.246435 a one
9.3 DataFrame 与dict 或者 Series 的index的交互groupby
people = DataFrame(np.random.randn(5, 5),columns=['a', 'b', 'c', 'd', 'e'],index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])people.ix[2:3, ['b', 'c']] = np.nan # Add a few NA values
mapping = {'a': 'red', 'b': 'red', 'c': 'blue', 'd': 'blue', 'e': 'red', 'f' : 'orange'}#dict 中的key与dataframe的列名称一致,用 dict 的值进行groupby
by_column = people.groupby(mapping, axis=1)by_column.sum()
输出:blue redJoe 0.503905 1.063885Steve 1.297183 -1.553778Wes -1.021228 -1.116829Jim 0.524712 1.770545Travis -4.230992 -2.405455
map_series = Series(mapping)people.groupby(map_series, axis=1).count()
#与dict类似,也是将Series的key与dataframe的列名做对照,将value进行groupby
people.groupby(map_series, axis=1).count()
输出:blue redJoe 2 3Steve 2 3Wes 1 2Jim 2 3Travis 2 3
9.4 对于DataFrame的columns命名
columns = pd.MultiIndex.from_arrays([['US', 'US', 'US', 'JP', 'JP'], [1, 3, 5, 1, 3]], names=['cty','tenor'])hier_df = DataFrame(np.random.randn(4, 5), columns=columns)hier_df.groupby(level='cty', axis=1).count()
输出:hier_df
cty US JP tenor 1 3 5 1 30 0.560145 -1.265934 0.119827 -1.063512 0.3328831 -2.359419 -0.199543 -1.541996 -0.970736 -1.3070302 0.286350 0.377984 -0.753887 0.331286 1.3497423 0.069877 0.246674 -0.011862 1.004812 1.327195
groupby的二阶层次:有多层列名的时候,用某一行列名总体的名称:
hier_df.groupby(level='cty', axis=1).count()Out[75]: cty JP US0 2 31 2 32 2 33 2 3
比较一阶层次:只有单层列名
df = DataFrame({'key1' : ['a', 'a', 'b', 'b', 'a'],'key2' : ['one', 'two', 'one', 'two', 'one'],'data1' : np.random.randn(5),'data2' : np.random.randn(5)})
grouped = df['data1'].groupby(df['key1'])
输出:dfOut[92]: data1 data2 key1 key20 -0.204708 1.393406 a one1 0.478943 0.092908 a two2 -0.519439 0.281746 b one3 -0.555730 0.769023 b two4 1.965781 1.246435 a one
groupedOut[93]: <pandas.core.groupby.SeriesGroupBy object at 0x0DDE2D70>
grouped.mean()Out[94]: key1a 0.746672b -0.537585Name: data1, dtype: float64
9.5 groupby 的聚合函数
python 提供了一些groupby的默认函数,例如 mean, sum, count, quantile (求样本分位数、中位数)等
若要自定义函数,则可以采用agg oraggregate方法:说明:自定义聚合函数比默认函数运行慢很多
dfgrouped = df.groupby('key1')def peak_to_peak(arr):return arr.max() - arr.min()grouped.agg(peak_to_peak)
输出:dfdata1 data2 key1 key20 -0.204708 1.393406 a one1 0.478943 0.092908 a two2 -0.519439 0.281746 b one3 -0.555730 0.769023 b two4 1.965781 1.246435 a one
grouped.agg(peak_to_peak)Out[112]: data1 data2key1 a 2.170488 1.300498b 0.036292 0.487276
9.6 DataFrame.groupby([col1],[col2],..).agg(function)agg的使用方法
grouped = tips.groupby(['sex', 'smoker'])grouped_pct = grouped['tip_pct']
grouped_pct.agg('mean')#等效于 grouped_pct..mean()
grouped_pct.agg([('foo', 'mean'), ('bar', np.std)])#对某一列做不同运算,得到多列结果,例:其中'foo'是列的名称,'mean'是具体算法
输出:Out[3]:foo barsex smokerFemale No 0.156921 0.036421Yes 0.182150 0.071595Male No 0.160669 0.041849Yes 0.152771 0.090588
grouped_pct.agg(['mean', 'std', peak_to_peak])#对某一列做三种运算输出:grouped_pct.agg(['mean', 'std', peak_to_peak])Out[4]:mean std peak_to_peaksex smokerFemale No 0.156921 0.036421 0.195876Yes 0.182150 0.071595 0.360233Male No 0.160669 0.041849 0.220186Yes 0.152771 0.090588 0.674707
functions = ['count', 'mean', 'max']result = grouped['tip_pct', 'total_bill'].agg(functions)#对两列数据,做三种运算
输出:resulttip_pct total_billcount mean max count mean maxsex smokerFemale No 54 0.156921 0.252672 54 18.105185 35.83Yes 33 0.182150 0.416667 33 17.977879 44.30Male No 97 0.160669 0.291990 97 19.791237 48.33Yes 60 0.152771 0.710345 60 22.284500 50.81

DataFrame.groupby().agg([('列名称1','func1'),('列名称2','func2')])ftuples = [('Durchschnitt', 'mean'), ('Abweichung', np.var)]grouped['tip_pct', 'total_bill'].agg(ftuples)#对两列数据,分别做相同的运算,并分别命名,例:待运算列'tip_pct','total_bill',运算方法 mean和np.var,分别命名

输出:tip_pct total_bill#列名Durchschnitt Abweichung Durchschnitt Abweichung#运算方法名称sex smoker Female No 0.156921 0.001327 18.105185 53.092422Yes 0.182150 0.005126 17.977879 84.451517Male No 0.160669 0.001751 19.791237 76.152961Yes 0.152771 0.008206 22.284500 98.244673
DataFrame.groupby([col1],[col2],..).agg(dict{col3: fuc3, col4: [fuc4, fuc5, fuc6], ....})
grouped.agg( {'tip_pct' : ['min', 'max', 'mean', 'std'],'sizes':'sum'})#对于两列,分别做不同的运算
输出:Out[29]: tip_pct sizesmin max mean std sumsex smoker Female No 0.056797 0.252672 0.156921 0.036421 140Yes 0.056433 0.416667 0.182150 0.071595 74Male No 0.071804 0.291990 0.160669 0.041849 263Yes 0.035638 0.710345 0.152771 0.090588 150
9.7 DataFrame.groupby('col1').transform(function)
transform可以将函数运用到各个分组中,并将结果放置到适当的位置上。
示例:
people = DataFrame(np.random.randn(5, 5),columns=['a', 'b', 'c', 'd', 'e'],index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])key = ['one', 'two', 'one', 'two', 'one']people.groupby(key).mean()
people.groupby(key).transform(np.mean)
def demean(arr):return arr - arr.mean()demeaned = people.groupby(key).transform(demean)demeaned
demeaned.groupby(key).mean()
输出:people.groupby(key).mean()Out[33]:a b c d eone 0.087580 -0.113431 1.001499 -0.449348 0.913870two 1.139918 -0.954365 -0.045048 1.219024 0.403933
people.groupby(key).transform(np.mean)Out[34]:a b c d eJoe 0.087580 -0.113431 1.001499 -0.449348 0.913870Steve 1.139918 -0.954365 -0.045048 1.219024 0.403933Wes 0.087580 -0.113431 1.001499 -0.449348 0.913870Jim 1.139918 -0.954365 -0.045048 1.219024 0.403933Travis 0.087580 -0.113431 1.001499 -0.449348 0.913870
demeanedOut[35]:a b c d eJoe -0.292288 0.592374 -1.520938 -0.106382 1.051911Steve 0.253488 1.047273 0.326794 -0.450001 0.842502Wes 0.919609 -1.182790 -0.726507 0.678261 0.439047Jim -0.253488 -1.047273 -0.326794 0.450001 -0.842502Travis -0.627322 0.590416 2.247445 -0.571879 -1.490957
9.8 dataframe.groupby('column1').apply(function)
apply(func):将函数func在dataframe各个片段上调用,由pandas.concat组装到一起,并以分组名称进行标记,结果得到一个层次化的索引

def top(df, n=5, column='tip_pct'):return df.sort_index(by=column)[-n:]top(tips, n=6)
tips.groupby('smoker').apply(top)
tips.groupby('smoker').apply(top, n=3, column='total_bill')#改变了函数top中的变量值
输出:tips.groupby('smoker').apply(top)Out[43]:total_bill tip sex smoker day time sizes tip_pctsmokerNo 88 24.71 5.85 Male No Thur Lunch 2 0.236746185 20.69 5.00 Male No Sun Dinner 5 0.24166351 10.29 2.60 Female No Sun Dinner 2 0.252672149 7.51 2.00 Male No Thur Lunch 2 0.266312232 11.61 3.39 Male No Sat Dinner 2 0.291990Yes 109 14.31 4.00 Female Yes Sat Dinner 2 0.279525183 23.17 6.50 Male Yes Sun Dinner 4 0.28053567 3.07 1.00 Female Yes Sat Dinner 1 0.325733178 9.60 4.00 Female Yes Sun Dinner 2 0.416667172 7.25 5.15 Male Yes Sun Dinner 2 0.710345
tips.groupby('smoker').apply(top, n=3, column='total_bill')Out[44]:total_bill tip sex smoker day time sizes tip_pctsmokerNo 156 48.17 5.00 Male No Sun Dinner 6 0.10379959 48.27 6.73 Male No Sat Dinner 4 0.139424212 48.33 9.00 Male No Sat Dinner 4 0.186220Yes 102 44.30 2.50 Female Yes Sat Dinner 3 0.056433182 45.35 3.50 Male Yes Sun Dinner 3 0.077178170 50.81 10.00 Male Yes Sat Dinner 3 0.196812
fill_mean = lambda g: g.fillna(g.mean())DataFrame.groupby('key').apply(fill_mean)#lambda的过程相当于define function
9.9numpy.random.permutation对数列重新排序
numpy.random.permutation(x)Randomly permute a sequence, or return a permuted range.
Examples>>>>>>np.random.permutation(10)array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])>>>>>>np.random.permutation([1,4,9,12,15])array([15, 1, 9, 4, 12])>>>>>>arr= np.arange(9).reshape((3,3))>>>np.random.permutation(arr)array([[6, 7, 8], [0, 1, 2], [3, 4, 5]])
示例二:
deck = Series(card_val, index=cards)输出: #原始Series的顺序deck[:13]Out[100]:AH 12H 23H 34H 45H 56H 67H 78H 89H 910H 10JH 10KH 10QH 10dtype: int64
def draw(deck, n=5):return deck.take(np.random.permutation(len(deck))[:n]) #Series.take( np.random.permutation( x )) 对于Series随机排列元素顺序,然后取前x个元素draw(deck,n=10)输出:Out[104]: 5H 54S 4QC 104C 43S 36C 64D 48H 84H 43H 3dtype: int64

9.10 加权平均 numpy.average(list1, weight = list2)
对于list1中的元素求平均,权重为list2
data= np.arange(6).reshape((3,2))>>>dataarray([[0, 1], [2, 3], [4, 5]])>>>np.average(data, axis=1, weights=[1./4,3./4])array([ 0.75, 2.75, 4.75])
>>>np.average(data, axis=1, weights=[10,30])# 计算过程是,10+30=40,10/40=0.25,30/40=0.75,data中的每个数乘上各自的权重,再加和array([ 0.75, 2.75, 4.75])
9.11 相关性分析df['col1'].corr(df[' col2'])DataFrame.corr()['col2']DataFrame.corrwith(Series)
具体解释见收藏文章 或 链接http://book.2cto.com/201512/58842.htmlhttp://www.xuebuyuan.com/2180573.html
示例:
x1 = list(np.arange(10))x2 = list(np.arange(10)*3+5)
x3 = pd.Series(np.random.randn(10))
dict1 = {'x1':x1, 'x2':x2}df = pd.DataFrame(dict1)
y1 = df['x1'].corr(df['x2'])
y2 = df.corr()['x2']
y3 = df.corrwith(df['x2'])#等效于df.corr()['x2'], DataFrame.corrwith(Series) 好处是Series可以不是DataFrame的组成部分,例如y4
y4 = df.corrwith(x3) #
9.12 statsmodels.api.OLS(Y,X).fit()最小二乘法,OLS回归系数
OLS指的是一般最小二乘,fit方法对回归方程进行估计,summary保存着计算的结果
示例:import statsmodels.api as smdef regress(data, yvar, xvars):Y = data[yvar]X = data[xvars]X['intercept'] = 1.result = sm.OLS(Y, X).fit() #线性拟合 y = ax + breturn result.params #将a和b作为返回值
by_year.apply(regress, 'AAPL', ['SPX']) #返回值,SPX一列即y = ax + b中的a,intercept即截距b

9.13 DataFrame.pivot_table([data1, data2], rows=[row1, row2], cols = col1, margins = True)
margin = True 对于所有数据的分组统计,结果显示为All列,所有数据的平均数
data1 和 data2是研究对象,row1 和 row2 内容打开为行名,col1中的内容打开成为列名,
tips.pivot_table(['tip_pct', 'sizes'], index=['sex', 'day'],columns='smoker', margins=True)Out[44]: tip_pct sizes smoker No Yes All No Yes Allsex day Female Fri 0.165296 0.209129 0.199388 2.500000 2.000000 2.111111Sat 0.147993 0.163817 0.156470 2.307692 2.200000 2.250000Sun 0.165710 0.237075 0.181569 3.071429 2.500000 2.944444Thur 0.155971 0.163073 0.157525 2.480000 2.428571 2.468750Male Fri 0.138005 0.144730 0.143385 2.000000 2.125000 2.100000Sat 0.162132 0.139067 0.151577 2.656250 2.629630 2.644068Sun 0.158291 0.173964 0.162344 2.883721 2.600000 2.810345Thur 0.165706 0.164417 0.165276 2.500000 2.300000 2.433333All 0.159328 0.163196 0.160803 2.668874 2.408602 2.569672
传入函数 aggfunctips.pivot_table('sizes', index=['time', 'sex', 'smoker'],columns='day', aggfunc='sum', fill_value=0)Out[45]: day Fri Sat Sun Thurtime sex smokerDinner Female No 2 30 43 2Yes 8 33 10 0Male No 4 85 124 0Yes 12 71 39 0Lunch Female No 3 0 0 60Yes 6 0 0 17Male No 0 0 0 50Yes 5 0 0 23
9.14 Series2 = Series1.map(dict)
对于Series1中元素,在dict的key中查找相应的value,找到后将value赋值给Series2。如果Series1中的元素,但是dict中没有包含,那么Series2相应位置上默认为NaN
9.15 Series2 = Series1.isin(list1 )
Series2类型为值为Trur 或者 False的SeriesSeries1中若包含list1中的元素,则值为True;若不包含,则值为False
s2.ix[:4]Out[66]: 0 False1 False2 False3 True4 False
9.16 dict.get(key, default=None)
参数
  • key -- 字典中要查找的键。
  • default -- 如果指定键的值不存在时,返回该默认值值。
返回值返回指定键的值,如果值不在字典中返回默认值None。
示例:dict={'Name':'Zara','Age':27}print"Value : %s"% dict.get('Age')print"Value : %s"% dict.get('Sex',"Never")print "Value : %s" % dict.get('Sex')
以上实例输出结果为:Value:27Value:NeverValue : None
9.17 Series2 = pandas.cut(Series1, array)
bins = np.array([0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000])labels = pd.cut(fec_mrbo.contb_receipt_amt, bins)#type is pandas.core.series.Series
# 将Series1中的元素,按照array划分的区间,进行归类
输出:labelsOut[45]: 411 (10, 100]412 (100, 1000]413 (100, 1000]414 (10, 100]415 (10, 100]416 (10, 100]417 (100, 1000]418 (10, 100]419 (100, 1000]701377 (10, 100]701378 (10, 100]701379 (100, 1000]701380 (1000, 10000]701381 (10, 100]701382 (100, 1000]701383 (1, 10]701384 (10, 100]701385 (100, 1000]Name: contb_receipt_amt, dtype: categoryCategories (8, object): [(0, 1] < (1, 10] < (10, 100] < (100, 1000] < (1000, 10000] < (10000, 100000] < (100000, 1000000] < (1000000, 10000000]]
9.18 pyshp 读写dbf文件, shapefile
https://pypi.python.org/pypi/pyshp/
关于shapefile的具体文件格式信息见9_shapefile
>>> import shapefile
>>> sf = shapefile.Reader("shapefiles/blockgroups")OR>>> sf = shapefile.Reader("shapefiles/blockgroups.shp")OR>>> sf = shapefile.Reader("shapefiles/blockgroups.dbf")
>>> myshp = open("shapefiles/blockgroups.shp", "rb")>>> mydbf = open("shapefiles/blockgroups.dbf", "rb")>>> r = shapefile.Reader(shp=myshp, dbf=mydbf)
9.18 statep020
画出地图
http://mapserver.org/input/vector/filegdb.htmlhttp://blog.csdn.net/asswclw/article/details/42690373https://gapanalysis.usgs.gov/padusapps/PADUS1-2_AcreagebyState.pdf
http://gis.stackexchange.com/questions/56984/unable-to-load-shapefile-using-pgshapeloader-shp2pgsql-gui-pgadmin3s-postgis

9.19 dir() 查询用法
功能:查看指定模块的功能列表,以及任意指定对象的功能列表。dir([ ])Out[19]: ['__add__','__class__','__contains__','__delattr__','__delitem__','__delslice__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getslice__','__gt__','__hash__','__iadd__','__imul__','__init__','__iter__','__le__','__len__','__lt__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__reversed__','__rmul__','__setattr__','__setitem__','__setslice__','__sizeof__','__str__','__subclasshook__','append','count','extend','index','insert','pop','remove','reverse','sort']
第十章 时间序列
10.1 时间序列的基础频率DBHT minSL msUMBMMSBMSW-MON、W-TUEWOM-1MON、WOM-2MONQ-JAN、Q-FEBBQ-JAN、BQ-FEBQS-JAN、QS-FEBBQS-JAN BQS-FEBA-JAN A-FEBBA-JAN BA-FEBAS-JAN AS-FEBBAS-JAN BAS-FEB


10.2 Series.tz_localize('str') 与 Series.tz_convert('str')的区别
rng = pd.date_range('3/7/2012 9:30', periods=10, freq='B')ts = Series(np.random.randn(len(rng)), index=rng)ts #此时 ts 未指定时区
ts1 = ts[:7].tz_localize('Europe/London')#此时对于ts1用ts赋值,指定时区ts2 = ts1[2:].tz_convert('Europe/Moscow')#此时用ts1对ts2赋值,ts1已经有时区,只需要转化时区
# 错误用法: ts3 = ts1.tz_localize('Europe/London') 此时ts1已经有时区,不能重新指定时区,只能转换时区
10.3 index = pd.PeriodIndex(list, freq = str)
values = ['2001Q3', '2002Q2', '2003Q1']index = pd.PeriodIndex(values, freq='Q-DEC')


10.4 pandas._period.Period.asfreq('X', how = 's' or 'e')
按‘X’的模式,获得's' 或者 ‘e’的信息
初始化Period:pd.Period(content, freq = 'X')
p = pd.Period('2012Q4', freq='Q-JAN')p1 = pd.Period('2012Q4')p1.asfreq('D', 'end')#Period('2012-12-31', 'D')
rng = pd.period_range('2011Q3', '2012Q4', freq='Q-JAN')ts = Series(np.arange(len(rng)), index=rng)ts
new_rng = (rng.asfreq('B', 'e') - 1).asfreq('T', 's') + 16 * 60ts.index = new_rng.to_timestamp()ts
'''new_rngOut[39]: PeriodIndex(['2010-10-28 16:00', '2011-01-28 16:00', '2011-04-28 16:00','2011-07-28 16:00', '2011-10-28 16:00', '2012-01-30 16:00'],dtype='period[T]', freq='T')tsOut[38]: 2010-10-28 16:00:00 02011-01-28 16:00:00 12011-04-28 16:00:00 22011-07-28 16:00:00 32011-10-28 16:00:00 42012-01-30 16:00:00 5dtype: int32'''
10.5 pandas.tslib.Timestamp = pandas._period.Period .to_timestamp(content, freq ='X')
将Period文件转化为pandas.tslib.Timestamp
p = pd.Period('2012Q4', freq='Q-JAN')p4pm = (p.asfreq('B', 'e') - 1).asfreq('T', 's') + 16 * 60 #B: 工作日,e:end ; T:分钟,s:start,16*60决定了下午四点p4pm
p4pm.to_timestamp()
也可以Series2 = Series1.to_timestamp(how = 'end' or 'begin')

10.6 pandas._period.Period = pandas.tslib.Timestamp.to_period('X')
Series2 = Series1.to_period('X')
rng = pd.date_range('1/29/2000', periods=6, freq='D')ts2 = Series(randn(6), index=rng)ts2.to_period('M')
pts = ts.to_period() #默认 to_period('M')pts'''2000-01 -0.6112522000-02 -0.1398922000-03 -0.021829'''
pts.to_timestamp(how='end')'''2000-01-31 -0.6112522000-02-29 -0.1398922000-03-31 -0.021829'''pts.to_timestamp('s')'''2000-01-01 -0.6112522000-02-01 -0.1398922000-03-01 -0.021829Freq: MS, dtype: float64'''
10.7 freq = 'Q-Jan' 和 freq = 'Q-May' 的区别
rng = pd.period_range('2011Q3', '2012Q4', freq='Q-JAN')x = rng.asfreq('B', 'e')x
输出:'''PeriodIndex(['2010-10-29', '2011-01-31', '2011-04-29', '2011-07-29','2011-10-31', '2012-01-31'],dtype='period[B]', freq='B')#注意最后一个数字是2012年1月31号'''
rng = pd.period_range('2011Q3', '2012Q4', freq='Q-MAY')x = rng.asfreq('B', 'e')x输出:'''PeriodIndex(['2011-02-28', '2011-05-31', '2011-08-31', '2011-11-30','2012-02-29', '2012-05-31'],dtype='period[B]', freq='B')#注意最后一个数字是2012年5月31号'''说明:- 2011Q3~2012Q4,仅起到 PeriodIndex中有多少个元素的作用;- freq = 'Q-JAN' 起到最后一个元素在几月份的作用;- 2012Q4 起到最后一个数字在哪一年的作用;
10.8 频率转换 .resample()
有点像groupby
Series2 = Series1.resample('X', how = 'mean' or other way, kind = 'period' or 'timestamp')
#kind默认为timestamp, 若为timestamp则显示日期;若为period,则显示月份
rng = pd.date_range('1/1/2000', periods=100, freq='D')ts = Series(randn(len(rng)), index=rng)ts.resample('M', how='mean')
ts.resample('M', how='mean', kind='period')
输出:ts.resample('M', how='mean')#等效于 ts.resample('M', how='mean', kind='timestamp')Out[113]: 2000-01-31 -0.1286512000-02-29 0.0826152000-03-31 0.0983932000-04-30 0.490155Freq: M, dtype: float64ts.resample('M', how='mean', kind='period')Out[114]: 2000-01 -0.1286512000-02 0.0826152000-03 0.0983932000-04 0.490155Freq: M, dtype: float64
10.9 Series.groupby(lambda x: ... ).mean()
period和groupby的结合使用
10.10 pandas.tseries.period.PeriodIndex = pd.data_range('date', periods= x, freq = 'Y')
10.11 ‘Q-DEC’的用法
appl_q = close_px['AAPL'].resample('Q-DEC', fill_method='ffill')#‘Q-DEC’决定了12-31肯定会出现在结果中,且frequency 为季度,其他月份按照freq推导#但最后一个数字是错的,close_px中并没有2011/12/31号,但appl_q中有2011/12/31号,值为close_px的最后一天2011/10/14的值#从2003-03-31 ~ 2011-12-31
appl_q1 = close_px['AAPL'].resample('Q-FEB', fill_method='ffill') #其实点为1月31号#从2003-02-28 ~ 2011-11-30
appl_q2 = close_px['AAPL'].resample('Q-APR', fill_method='ffill')#从2003-01-31,2003-04-30 ~ 2011-11-30
10.12 .rolling_mean(Series, number).
pd.rolling_mean(close_px.AAPL, 250).plot()
相当于是取简略趋势图
250意思是点与点的跨度大小
pd.rolling_mean(close_px.AAPL, 25).plot()
pd.rolling_mean(close_px.AAPL, 250).plot()

pd.rolling_mean(close_px.AAPL, 1000).plot()
10.13 .ewma(Series, span = number)
EWMA 指数加权移动平均#该方法用于金融,目前只需要泛泛的了解什么时候真用到了,再学
EWMA(Exponentially Weighted Moving Average)指数加权移动平均,是一种常用的序列数据处理方式。在t时刻,根据实际的观测值可以求取EWMA(t):EWMA(t) = aY(t) + (1-a)EWMA(t-1),t = 1,2,.....,n;其中,EWMA(t) t时刻的估计值;Y(t) t时刻的测量值;n 所观察的总的时间;a(0 < a <1)表示对于历史测量值权重系数。之所以称之为指数加权,是因为加权系数a是以指数式递减的,即各指数随着时间而指数式递减。用n表示为a = 2/(n+1)。 物理意义:系数a越接近1表示对当前抽样值的权重越高,对过去测量值得权重越低,估计值(器)的时效性就越强,反之,越弱;另外,EWMA还有一定的吸收瞬间突发的能力,也即平稳性,显然随着a减小,参考过去测量值的程度更多一些,平稳性增强,反之则降低。
for


Expanding outeach time results in the following power series, showing how the weighting factor on each datum pointp1,p2, etc., decreases exponentially:where
  • is
  • is
  • and so on
since.
10.14 dataframe常用统计方法

count 非 NA 值的数量
describe 针对 Series 或 DF 的列计算汇总统计
min , max 最小值和最大值
argmin , argmax 最小值和最大值的索引位置(整数)
idxmin , idxmax 最小值和最大值的索引值
quantile 样本分位数(0 到 1)
sum 求和
mean 均值
median 中位数
mad 根据均值计算平均绝对离差
var 方差
std 标准差
skew 样本值的偏度(三阶矩)
kurt 样本值的峰度(四阶矩)
cumsum 样本值的累计和
cummin , cummax 样本值的累计最大值和累计最小值
cumprod 样本值的累计积
diff 计算一阶差分(对时间序列很有用)
pct_change 计算百分数变化

10.14 DataFrame.pct_change() 相等于 DF / DF.shift(1) - 1
spx_rets = spx_px / spx_px.shift(1) - 1 #用2003-01-03的值除以2003-01-02的值returns = spx_px.pct_change() #等于spx_rets
输出:spx_retsOut[12]: 2003-01-02 NaN2003-01-03 -0.0004842003-01-06 0.0224742003-01-07 -0.0065452003-01-08 -0.0140862003-01-09 0.0193862011-10-07 -0.0081632011-10-10 0.0341252011-10-11 0.0005442011-10-12 0.0097952011-10-13 -0.0029742011-10-14 0.017380Name: SPX, dtype: float64
10.15 两个Series的相关系数 pd.rolling_corr()
pd.rolling_corr(Series1 or DF, Series2, number1, min_periods = number2)
pandas.rolling_corr(arg1,arg2=None,window=None,min_periods=None,freq=None,center=False,pairwise=None,how=None)
1.若b≠0
Cov(X,Y) =E(XY) −E(X)E(Y) =bσ2若b=0,则ρXY= 0
2.标准差D (X ) = E [X - E(X)]2根号D (X )为 X 的均方差或标准差常用公式D(X)=E(X2)-E2(X)协方差COV(X,Y)=E([X-E(X)][Y-E(Y)])相关系数协方差/[根号D(X)*根号D(Y)]
复习概率论
3.
广告投入(万元)
x
月均销售额(万元)
y
x^2 y2 xy
1
2
3
4
5
6
7
8
9
10
12.5
15.3
23.2
26.4
33.5
34.4
39.4
45.2
55.4
60.9
21.2
23.9
32.9
34.1
42.5
43.2
49.0
52.8
59.4
63.5
156.25
234.09
538.24
696.96
1122.25
1183.36
1552.36
2043.04
3069.16
3708.81
449.44
571.21
1082.41
1162.81
1806.25
1866.24
2401.00
2787.84
3528.36
4032.25
265.00
365.67
763.28
900.24
1423.75
1486.08
1930.60
2386.56
3290.76
3867.15
合计 346.2 422.5 14304.52 19687.81 16679.09
=0.9942  相关系数为0.9942,说明广告投入费与月平均销售额之间有高度的线性正相关关系。
Python 相关系数
pd.rolling_corr(Series1 or DF, Series2, number1, min_periods = number2)
arg1: Series, DataFrame, or ndarrayarg2: Series, DataFrame, or ndarray, optionalif not supplied then will default to arg1 and produce pairwise outputwindow: intSize of the moving window. This is the number of observations used for calculating the statistic.min_periods: int, default NoneMinimum number of observations in window required to have a value (otherwise result is NA).freq: string or DateOffset object, optional (default None)Frequency to conform the data to before computing the statistic. Specified as a frequency string or DateOffset object.center: boolean, default FalseSet the labels at the center of the window.how: string, default ‘None’Method for down- or re-samplingpairwise: bool, default FalseIf False then only matching columns between arg1 and arg2 will be used and the output will be a DataFrame. If True then all pairwise combinations will be calculated and the output will be a Panel in the case of DataFrame inputs. In the case of missing elements, only complete pairwise observations will be used.
例:
dfOut[60]: x y1 12.5 21.22 15.3 23.93 23.2 32.94 26.4 34.15 33.5 42.56 34.4 43.27 39.4 49.08 45.2 52.89 55.4 59.410 60.9 63.5
corr_df = pd.rolling_corr(df.x,df.y,10)
corr_dfOut[62]: 1 NaN2 NaN3 NaN4 NaN5 NaN6 NaN7 NaN8 NaN9 NaN10 0.994198 #默认min_periods=windows=10dtype: float64
corr_df = pd.rolling_corr(df.x,df.y,10,min_periods=8)#10是整个窗口的大小,8是参与计算的最小窗口
corr_dfOut[64]: 1 NaN2 NaN3 NaN4 NaN5 NaN6 NaN7 NaN8 0.997764 #计算窗口 1-89 0.994526 #计算窗口1-910 0.994198 #计算的整个窗口,从1~10,x[1~10], y[1-10]作为两个数列,计算之间的相关系数dtype: float64
corr_df = pd.rolling_corr(df.x,df.y,8,min_periods=8)
corr_dfOut[66]: 1 NaN2 NaN3 NaN4 NaN5 NaN6 NaN7 NaN8 0.997764 #计算窗口1~89 0.993015 #计算窗口2~910 0.992727 #计算窗口3~10dtype: float64

第十一章
11.1 获取yahoo.finance的数据 -- pandas_datareader.data
http://pandas-datareader.readthedocs.io/en/latest/remote_data.html#yahoo-finance


示例1:
import pandas_datareader.data as webimport datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2013, 1, 27)
f = web.DataReader("F", 'yahoo', start, end)

示例2:
amzn = web.get_quote_yahoo('AMZN')
amzn
关于 pandas_datareader的使用说明dir(pandas_datareader)Out[45]: ['__builtins__','__doc__','__file__','__name__','__package__','__path__','__version__','_utils','base','data','eurostat','famafrench','fred','google','io','oecd','version','wb' #world bank'yahoo']
关于 pandas_datareader.data 的使用说明import pandas_datareader.data as web
dir(web)Out[42]: ['DataReader','EurostatReader','FamaFrenchReader','FredReader','GoogleDailyReader','OECDReader','Options','YahooActionReader','YahooDailyReader','YahooOptions','YahooQuotesReader','__builtins__','__doc__','__file__','__name__','__package__','get_components_yahoo','get_data_famafrench','get_data_fred','get_data_google','get_data_yahoo','get_data_yahoo_actions','get_quote_google','get_quote_yahoo','warnings']
关于 pandas_datareader.data.get_data_yahoo 的使用说明
dir(web.get_data_yahoo)Out[41]: ['__call__','__class__','__closure__','__code__','__defaults__','__delattr__','__dict__','__doc__','__format__','__get__','__getattribute__','__globals__','__hash__','__init__','__module__','__name__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','func_closure','func_code','func_defaults','func_dict','func_doc','func_globals','func_name']
11.2 分析两组数据的相关性工具 statsmodels
statsmodels.formula.api
from pandas_datareader import wbimport numpy as npimport statsmodels.formula.api as smf
wb.search('gdp.*capita.*const').iloc[:,:2] #compare the Gross Domestic Products per capita in constant dollars in North America
dat = wb.download(indicator='NY.GDP.PCAP.KD', country=['US', 'CA', 'MX'], start=2005, end=2008)print(dat)dat['NY.GDP.PCAP.KD'].groupby(level=0).mean()
wb.search('cell.*%').iloc[:,:2] #compare GDP to the share of people with cellphone contracts around the world.
ind = ['NY.GDP.PCAP.KD', 'IT.MOB.COV.ZS']dat = wb.download(indicator=ind, country='all', start=2011, end=2011).dropna()dat.columns = ['gdp', 'cellphone']print(dat.tail())
import numpy as npimport statsmodels.formula.api as smf#statsmodels package to assess the relationship between our two variables using ordinary least squares regression.
mod = smf.ols("cellphone ~ np.log(gdp)", dat).fit()print(mod.summary())
输出:mod.summary()Out[93]: <class 'statsmodels.iolib.summary.Summary'>"""OLS Regression Results==============================================================================Dep. Variable: cellphone R-squared: 0.323Model: OLS Adj. R-squared: 0.299Method: Least Squares F-statistic: 13.38Date: Wed, 11 Jan 2017 Prob (F-statistic): 0.00104Time: 11:15:49 Log-Likelihood: -127.20No. Observations: 30 AIC: 258.4Df Residuals: 28 BIC: 261.2Df Model: 1 Covariance Type: nonrobust===============================================================================coef std err t P>|t| [95.0% Conf. Int.]-------------------------------------------------------------------------------Intercept -2.1117 23.866 -0.088 0.930 -50.999 46.775np.log(gdp) 11.9623 3.271 3.657 0.001 5.262 18.662==============================================================================Omnibus: 27.980 Durbin-Watson: 2.062Prob(Omnibus): 0.000 Jarque-Bera (JB): 64.430Skew: -1.942 Prob(JB): 1.02e-14Kurtosis: 9.038 Cond. No. 55.9==============================================================================
Warnings:[1] Standard Errors assume that the covariance matrix of the errors is correctly specified."""11.3 pandas_datareader.data
import pandas_datareader.data as webimport datetime
可以获得 yahoo.finance的数据f = web.DataReader("F", 'yahoo', start, end)f1=web.get_data_yahoo('AAPL','1/1/2014','20/8/2015')amzn = web.get_quote_yahoo('AMZN') #获得股票概况
f2 = web.DataReader('AAPL', 'yahoo-actions', start, end) #查看股息 dividend 和股票分割stock split
获得深圳股票市场上市公司的数据:濮阳惠成(SZ:300481)Huicheng=web.get_data_yahoo('300481.sz','1/1/2015','20/8/2015')
获得上海股票市场上市公司的数据:复旦复华(SH:600624)web.get_data_yahoo('600624.ss','7/1/2015','8/20/2015')
上证股票是股票代码后面加上.ss,深证股票是股票代码后面加上.sz上证综指代码:000001.ss,深证成指代码:399001.SZ,沪深300代码:000300.ss;香港为 0001.hk;
香港股指代码为 .hk加拿大股指代码:cnu.to;新西兰股指代码为.nz新加坡股指代码为.si;台湾股指代码为.tw


可以获得美联储的数据 FRED# FRED: Federal Reserve Bank of St. Louis 美国联邦储备银行
gdp = web.DataReader("GDP", "fred", start, end)inflation = web.DataReader(["CPIAUCSL", "CPILFESL"], "fred", start, end)
inflation.head()
# CPIAUCSL: Consumer Price Index for All Urban Consumers: All Items (CPIAUCSL)# CPILFESL: the core CPI (Consumer Price Index for All Urban Consumers: All Items Less Food & Energy [CPILFESL])
访问 Fama/French Data Library 数据库# Fama/French: Fama-French三因子模型,访问 Fama/French Data Library 数据库 get_available_datasets
ds = web.DataReader("5_Industry_Portfolios", "famafrench")
ds[4].ix[:1]Out[11]: Cnsmr Manuf HiTec Hlth OtherDate 2010-01 622 737 835 468 1236
可以获得 世界银行 的数据 WB -- WorldBank
wb.search('gdp.*capita.*const').iloc[:,:2] #compare the Gross Domestic Products per capita in constant dollars in North America
dat = wb.download(indicator='NY.GDP.PCAP.KD', country=['US', 'CA', 'MX'], start=2005, end=2008)
ind = ['NY.GDP.PCAP.KD', 'IT.MOB.COV.ZS']dat = wb.download(indicator=ind, country='all', start=2011, end=2011).dropna()dat.columns = ['gdp', 'cellphone']
可以获得 经合组织 的数据 OECD
df = web.DataReader('UN_DEN', 'oecd', end=datetime.datetime(2012, 1, 1))#工会密度Trade Union Density” data which set code is “UN_DEN”.

可以获得 欧盟统计局 的数据 Eurostat
df = web.DataReader("tran_sf_railac", 'eurostat') #tran_sf_railac: Rail accidents by type of accident
11.4 ffillNaN的部分与上一元素保持一致
ts1Out[5]: 2012-06-13 -0.2831282012-06-20 -0.2114892012-06-27 0.213811
x = ts1.resample('B', fill_method='ffill')
xOut[10]: 2012-06-13 -0.2831282012-06-14 -0.2831282012-06-15 -0.2831282012-06-18 -0.2831282012-06-19 -0.2831282012-06-20 -0.2114892012-06-21 -0.2114892012-06-22 -0.2114892012-06-25 -0.2114892012-06-26 -0.2114892012-06-27 0.213811Freq: B, dtype: float64
11.5 Series.reindex(PeriodIndex, method = 'ffill' or 'dropna' etc.)
11.6将该时间序列大部分内容随机设置为NAindexer = np.sort(np.random.permutation(len(ts))[700:])#产生860个随机数,再从小到大排列,ts总长度为1560个,取其中的700往后的860个,再按从小到大排列irr_ts = ts.copy()irr_ts[indexer] = np.nan


numpy.random.permutation // 随机重排序
sampler = np.random.permutation(5)// 产生5个一组的随机数
输出:samplerOut[52]: array([2, 1, 3, 0, 4])
11.7 Series.copy()
11.8 numpy.copy待复制的元数据改变了,新生产的数字保持不变x = np.array([1, 2, 3])y = xz = np.copy(x)
x[0] = 10
输出:xOut[73]: array([10, 2, 3])
yOut[74]: array([10, 2, 3])
zOut[75]: array([1, 2, 3])
11.9 Series.asof(DatetimeIndex)
selection = pd.date_range('2012-06-01 10:00', periods=4, freq='B')irr_ts.asof(selection) #本来2012-06-01 10:00位置数值可能为NaN,.asof()之后变为取之前最近一个数字
'''2012/6/6 9:57 11972012/6/6 9:582012/6/6 9:592012/6/6 10:00
irr_ts.asof(selection)
2012-06-06 10:00:00 1197.0将2012/6/6 9:57的值赋给了 2012/6/6 10:00'''
11.10 pandas.concat([Series1, Series2, Series3], axis =0 or 1)#若为0,则仍为Series; 若为1,则变成DataFrame
spliced_filled = spliced.combine_first(data2)将spliced与data2结合
data1 = DataFrame(np.ones((6, 3), dtype=float),columns=['a', 'b', 'c'],index=pd.date_range('6/12/2012', periods=6))
data2 = DataFrame(np.ones((6, 4), dtype=float) * 2,columns=['a', 'b', 'c', 'd'],index=pd.date_range('6/13/2012', periods=6))spliced = pd.concat([data1.ix[:'2012-06-14'], data2.ix['2012-06-15':]])spliced
输出:data1Out[100]: a b c2012-06-12 1.0 1.0 1.02012-06-13 1.0 1.0 1.02012-06-14 1.0 1.0 1.02012-06-15 1.0 1.0 1.02012-06-16 1.0 1.0 1.02012-06-17 1.0 1.0 1.0
data2Out[101]: a b c d2012-06-13 2.0 2.0 2.0 2.02012-06-14 2.0 2.0 2.0 2.02012-06-15 2.0 2.0 2.0 2.02012-06-16 2.0 2.0 2.0 2.02012-06-17 2.0 2.0 2.0 2.02012-06-18 2.0 2.0 2.0 2.0
splicedOut[102]: a b c d2012-06-12 1.0 1.0 1.0 NaN2012-06-13 1.0 1.0 1.0 NaN2012-06-14 1.0 1.0 1.0 NaN2012-06-15 2.0 2.0 2.0 2.02012-06-16 2.0 2.0 2.0 2.02012-06-17 2.0 2.0 2.0 2.02012-06-18 2.0 2.0 2.0 2.0
---spliced_filled = spliced.combine_first(data2)spliced_filled
Out[103]: a b c d2012-06-12 1.0 1.0 1.0 NaN2012-06-13 1.0 1.0 1.0 2.02012-06-14 1.0 1.0 1.0 2.02012-06-15 2.0 2.0 2.0 2.02012-06-16 2.0 2.0 2.0 2.02012-06-17 2.0 2.0 2.0 2.02012-06-18 2.0 2.0 2.0 2.0
11.11 Series.cumprod()
price = web.get_data_yahoo('AAPL', '2011-01-01')['Adj Close'] #Adj Close: 已调整收盘价 adjusted closing priceprice[-5:]
price['2011-10-03'] / price['2011-3-01'] - 1
returns = price.pct_change() #DataFrame.pct_change() 相等于 DF / DF.shift(1) - 1ret_index = (1 + returns).cumprod() #.cumprod() 简单计算综合考虑派息、稀释股票后的收益指数ret_index[0] = 1 # Set first value to 1ret_index
11.12 random.xxx 用法
11.13 DF1 = DataFrameGroupBy.rank(ascending = True or False)
SeriesGroupBy = Series1.groupby(Series2)
其中Series1的index和Series2相同
ind_names = np.array(['FINANCIAL', 'TECH'])sampler = np.random.randint(0, len(ind_names), N) #在0和len(ind_names)任选一个数,选N次,组成数组industries = Series(ind_names[sampler], index=tickers,name='industry') #将股票分为两类
by_industry = df.groupby(industries) #按照industries中的分类,进行groupbyby_industry.mean()
by_industry = df.groupby(industries)
ind_rank = by_industry.rank(ascending=False) #获得排名的次序
输出:
dfOut[165]: Momentum ShortInterest ValueVTKGN 0.028976 -0.024918 0.076191KUHMP 0.032395 -0.015345 0.078342... ... ...YQQAD 0.037447 -0.018743 0.083095PTDQE 0.036321 -0.011877 0.086869
[500 rows x 3 columns]


by_industryOut[166]: <pandas.core.groupby.DataFrameGroupBy object at 0x000000000D5090B8>
ind_rankOut[167]: Momentum ShortInterest ValueVTKGN 130.0 193.0 195.0#rank获得df中value在该列的排名KUHMP 67.0 31.0 149.0XNHTQ 162.0 183.0 243.0... ... ...
YQQAD 8.0 85.0 54.0PTDQE 33.0 20.0 26.0
[500 rows x 3 columns]
11.14 pandas.ols(y=Series, x=DF_factors).beta最小二乘回归暴露计算因子的权重??
from numpy.random import randfac1, fac2, fac3 = np.random.rand(3, 1000) #fac1 为array,元素数量为1000
ticker_subset = tickers.take(np.random.permutation(N)[:1000])
# Weighted sum of factors plus noiseport = Series(0.7 * fac1 - 1.2 * fac2 + 0.3 * fac3 + rand(1000),index=ticker_subset)factors = DataFrame({'f1': fac1, 'f2': fac2, 'f3': fac3},index=ticker_subset)

factors.corrwith(port) #求相关性

pd.ols(y=port, x=factors).beta#最小二乘回归,暴露计算因子
11.15Python cumsums和cumprod函数
>>>a = np.array([1,2,3],[4,5,6]]) >>>a array([[1,2,3], [4,5,6]]) >>>a.cumsum(0)#累计求和 array([[1,2,3], [5,7,9]]) >>>a.cumprod(1)#累计求积array([[1,2,6], [4,20,120]])
这两个函数中难点就是其中参数0,1其中0代表列的计算,1代表行的计算,即对列和行分别累积求和、 积。而且其结果不聚合,产生的是中间数组。
11.16pandas.rolling_sum 求窗口内的和,pandas.rolling_sum(arg,window,min_periods=None,freq=None,center=False,how=None,**kwargs)Moving sum.
Parameters:
arg : Series, DataFramewindow : intSize of the moving window. This is the number of observations used for calculating the statistic.min_periods :int, default NoneMinimum number of observations in window required to have a value (otherwise result is NA).freq: string or DateOffset object, optional (default None)Frequency to conform the data to before computing the statistic. Specified as a frequency string or DateOffset object.center: boolean, default FalseSet the labels at the center of the window.how :string, default ‘None’Method for down- or re-sampling
示例:signal = pd.rolling_sum(rets, 7, min_periods=2)#说明:7为windows,即加和计算的最大
11.17 Series.idxmax() 见文章11.17
Series 中还有一对ser.idxmax()ser.idxmin()方法,可以返回数组中最大(小)值的索引值,或者.argmin().argmax()返回索引位置。当然这两类方法也是可以通过上面这种ser[ser=ser.max()]来替代实现的。
其他常用的统计方法有:
count 非 NA 值的数量
describe 针对 Series 或 DF 的列计算汇总统计
min , max 最小值和最大值
argmin , argmax 最小值和最大值的索引位置(整数)
idxmin , idxmax 最小值和最大值的索引值
quantile 样本分位数(0 到 1)
sum 求和
mean 均值
median 中位数
mad 根据均值计算平均绝对离差
var 方差
std 标准差
skew 样本值的偏度(三阶矩)
kurt 样本值的峰度(四阶矩)
cumsum 样本值的累计和
cummin , cummax 样本值的累计最大值和累计最小值
cumprod 样本值的累计积
diff 计算一阶差分(对时间序列很有用)
pct_change 计算百分数变化

11.18 pandas.qcutpandas.qcut(x,q,labels=None,retbins=False,precision=3)[source]
示例:>>>pd.qcut(range(5),4)#按值分为四个区间[[0, 1], [0, 1], (1, 2], (2, 3], (3, 4]]Categories (4, object): [[0, 1] < (1, 2] < (2, 3] < (3, 4]]
>>>pd.qcut(range(5),3, labels=["good","medium","bad"])[good, good, medium, bad, bad]Categories (3, object): [good < medium < bad]
>>>pd.qcut(range(5),4, labels=False)array([0, 0, 1, 2, 3], dtype=int64)
11.19 fillna(method='pad')pad / ffill ->Fill values forwardbfill / backfill -> Fill values backward
详细说明见 文章11.19 Working with missing data
11.20 画热力图import matplotlib.pyplot as plt
def heatmap(df, cmap=plt.cm.gray_r): #画出热图 heatmapfig = plt.figure()ax = fig.add_subplot(111)axim = ax.imshow(df.values, cmap=cmap, interpolation='nearest')ax.set_xlabel(df.columns.name)ax.set_xticks(np.arange(len(df.columns)))ax.set_xticklabels(list(df.columns))ax.set_ylabel(df.index.name)ax.set_yticks(np.arange(len(df.index)))ax.set_yticklabels(list(df.index))plt.colorbar(axim)

heatmap(ddf) # ddf type is dataframe

第十二章 Numpy的高级用法
12.1 dtype.mro() 查看其所有父类
np.float64.mro()
输出:[numpy.float64,numpy.floating,numpy.inexact,numpy.number,numpy.generic,float,object]
12.2 numpy.ndarray.reshape()将一维数组转化为多位数组
逆过程:多维数组转化为一维数组,即扁平化:floattening, raveling,说明:默认模式为行优先,先存第一行数据,然后第二行,然后第三行,以此类推
扁平化中的列优先,即先把第一列的数据存在一维数组数组中,然后第二列,然后第三列 ,以此类推: ' ‘F’(即模仿Fortran语言)
行优先:'C' (即模仿C语言),默认状态下为行优先
示例:arr = np.arange(15).reshape((5, 3))arrarr.ravel()arr.flatten()
输出:Out[295]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
arrOut[296]: array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11],[12, 13, 14]])
arr.ravel()Out[297]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])arr.flatten()Out[298]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
arr.flatten('F')Out[300]: array([ 0, 3, 6, 9, 12, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14])
arr.flatten('C')Out[301]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

12.3 数组的合并np.concatenate, vstack, hstack
array3 = np.concatenate([array1, array2], axis = 0 or 1)
行优先:array3 = np.concatenate([array1, array2], axis = 0)等效于np.vstack((arr1,arr2))
列优先:array3 = np.concatenate([array1, array2], axis = 1)等效于np.hstack((arr1,arr2))
12.4 数组的拆分numpy.splitnumpy.split(ary,indices_or_sections,axis=0)[source]Split an array into multiple sub-arrays.
示例:>>>x= np.arange(9.0)>>>np.split(x,3)#np.split(arr, n) 将数组拆为n等分[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])]>>>>>>x= np.arange(8.0)>>>np.split(x, [3,5,6,10])#np.split(arr, list) 比如,np.split(arr, [n1,n2,n3,...]) 拆后的第一个元素包含n1个数字,第二个元素+第一个元素包含n2个数字,前三个元素包含n3个数字[array([ 0., 1., 2.]), #第一个元素包含3个数字 array([ 3., 4.]),#前两个数组包含5个元素 array([ 5.]),#前三个数组包含6个元素 array([ 6., 7.]),#前四个数组包含10个元素,但x的总数字数小于10,故显示出所有剩余数字 array([], dtype=float64)]#最后一个为空,因为元素数组x中不足10个数字,故补一个空数组
12.5 r_ 和 c_ 使数组的堆叠格式更简洁
arr = np.arange(6)arr1 = arr.reshape((3, 2))arr2 = randn(3, 2)np.r_[arr1, arr2]np.c_[np.r_[arr1, arr2], arr]
输出:np.r_[arr1, arr2]Out[346]: array([[ 0. , 1. ],[ 2. , 3. ],[ 4. , 5. ],[-0.1654, -0.6004],[ 0.0538, -0.5486],[-0.4473, -0.3284]])
np.c_[np.r_[arr1, arr2], arr]Out[347]: array([[ 0. , 1. , 0. ],[ 2. , 3. , 1. ],[ 4. , 5. , 2. ],[-0.1654, -0.6004, 3. ],[ 0.0538, -0.5486, 4. ],[-0.4473, -0.3284, 5. ]])
12.6 元素的重复操作: repeat 数字重复 和 tile 数组堆叠
tile(x, ())
arr = np.arange(3)arr.repeat(3) #每个数字重复三次
arr.repeat([2, 3, 4])#第一个数字重复2次,第二个数字重复3次,第三个4次输出:array([0, 0, 1, 1, 1, 2, 2, 2, 2])

--arr = randn(2, 2)arr.repeat([2, 3], axis=0)arr.repeat([2, 3], axis=1)
输出:arrOut[355]: array([[ 0.3795, -0.8685],[ 0.0849, -1.4308]])

arr.repeat([2, 3], axis=0)Out[356]: array([[ 0.3795, -0.8685],[ 0.3795, -0.8685],[ 0.0849, -1.4308],[ 0.0849, -1.4308],[ 0.0849, -1.4308]])
arr.repeat([2, 3], axis=1)Out[357]: array([[ 0.3795, 0.3795, -0.8685, -0.8685, -0.8685],[ 0.0849, 0.0849, -1.4308, -1.4308, -1.4308]])
.tile 堆叠
arrnp.tile(arr, 2)np.tile(arr, (3, 2))
输出:arrOut[360]: array([[ 0.3795, -0.8685],[ 0.0849, -1.4308]])
np.tile(arr, 2)Out[361]: array([[ 0.3795, -0.8685, 0.3795, -0.8685],[ 0.0849, -1.4308, 0.0849, -1.4308]])
np.tile(arr, (3, 2)) #按行,将整个矩阵重复3次;按列,重复2次Out[362]: array([[ 0.3795, -0.8685, 0.3795, -0.8685],[ 0.0849, -1.4308, 0.0849, -1.4308],[ 0.3795, -0.8685, 0.3795, -0.8685],[ 0.0849, -1.4308, 0.0849, -1.4308],[ 0.3795, -0.8685, 0.3795, -0.8685],[ 0.0849, -1.4308, 0.0849, -1.4308]])
12.7 花式索引的等价函数: arr.take(list), arr.put(list1, number or list2)
arr = np.arange(10) * 100inds = [7, 1, 2, 6]
#花式索引arr[inds]
#take 形式 等效于 花式索引arr.take(inds)
输出:arr[inds] Out[363]: array([700, 100, 200, 600])
arr.take(inds)Out[364]: array([700, 100, 200, 600])
示例2:inds = [2, 0, 2, 1]arr = randn(2, 4)arrarr.take(inds, axis=1)
输出:arrOut[366]: array([[-0.3507, 0.0533, -0.2497, -0.0806],[-0.1212, -1.8735, 1.2931, -1.4743]])
arr.take(inds, axis=1)Out[367]: array([[-0.2497, -0.3507, -0.2497, 0.0533],[ 1.2931, -0.1212, 1.2931, -1.8735]])

put:说明,put不接受axis参数,只能在一维数组上进行索引arr = np.arange(10) * 100inds = [7, 1, 2, 6]arr.put(inds, [40, 41, 42, 43])
输出:arr.put(inds, [40, 41, 42, 43])
array([ 0, 41, 42, 300, 400, 500, 43, 40, 800, 900])#替换元素
12.8 计算两个数组的 叉积
arr = np.arange(3).repeat([1, 2, 2])arrnp.multiply.outer(arr, np.arange(5))
输出:array([0, 1, 1, 2, 2])
Out[389]: array([[0, 0, 0, 0, 0],[0, 1, 2, 3, 4],[0, 1, 2, 3, 4],[0, 2, 4, 6, 8],[0, 2, 4, 6, 8]])
12.9 numpy.add.reduceat( array, list, axis = 0 or 1)
reduceat方法计算多组reduce的结果,通过indices参数指定一系列reduce的起始和终了位置。reduceat的计算有些特别,让我们通过一个例子来解释一下:>>>a= np.array([1,2,3,4])>>>indices=[0,1,0,2,0,3,0]>>>result= np.add.reduceat(a, indices)>>>resultarray([ 1, 2, 3, 3, 6, 4, 10])对于indices中的每个元素都会调用reduce函数计算出一个值来,因此最终计算结果的长度和indices的长度相同。结果result数组中除最后一个元素之外,都按照如下计算得出:
第一个元素计算规律:if indices[i] > indices[i+1]: result[i] = a[ indices[i] ]else:result[i] = np.reduce(a[indices[i]:indices[i+1]])
非首末元素的计算规律:if indices[i-1] > indices[i] && indices[i] < indices[i+1]result[i] = np.reduce(a[indices[i]:indices[i+1]]) else:result[i] = a[ indices[i] ]
而最后一个元素如下计算:np.add.reduce(a[indices[i]:])
因此上面例子中,结果的每个元素如下计算而得:0 : a[0] = 1#因为indices[0]<indices[1],即0<1, 所以result[0] = a[indices[0]: indices[1]] = a[0:1] =a[0]=11 : a[1] = 2 2 : a[0] + a[1] = 1 + 2 3 : a[2] = 3 4 : a[0] + a[1] + a[2] = 1 + 2 + 3 = 6= a[0]+a[1]+a[2]5 : a[3] = 46 : np.add.reduce(a[indices[6]:]) = np.add.reduce(a[0:]) = 10
可以看出result[::2]和a相等,而result[1::2]和np.add.accumulate(a)相等。
示例2:arr = np.arange(12)+30a= [5, 0, 6,7,4,3,2,1,7,8,9,10]result = np.add.reduceat( arr, a)
输出:Out[435]: array([ 35, 195, 36, 37, 34, 33, 32, 201, 37, 38, 39, 81])
分析:在list [5, 0, 6,7,4,3,2,1,7,8,9,10] 中,除了首末元素以外,找出数字趋势开始上升的拐点,即这些点的数字比左右两边都小[5, 0, 6,7,4,3,2,1,7,8,9,10]
这些点的计算方法如下,result[i] = np.reduce(a[indices[i]:indices[i+1]])
除了这些点以外,其他点计算方法为:result[i] = a[ indices[i] ]
35:因为a[0]>a[1],故result[0] = arr[a[0]]=arr[5]=35195: 0<5 && 0<6, 故result[1] = sum(arr[a[1]]: arr[a[2]])=sum(arr[0]:arr[6])=19536: 因为6>0,故result[2]=arr[a[6]]=3681: sum(arr[a[11]]: )=sum(arr[10]:) = arr[11]+arr[12]=81
12.10 NumPy-快速处理数据
见文章12.10
12.11 记录式数组 dtype
示例一:dtype = [('x', np.float64), ('y', np.int32)]sarr = np.array([(1.5, 6), (np.pi, -2)], dtype=dtype)sarr[0]['y']sarr['x']
输出:
sarr[0]['y']Out[458]: 6
sarr['x']Out[459]: array([ 1.5 , 3.1416])
示例二:dtype = [('x', [('a', 'f8'), ('b', 'f4')]), ('y', np.int32)]data = np.array([((1, 2), 5), ((3, 4), 6)], dtype=dtype)data['x']data['y']data['x']['a']
输出:dataOut[461]: array([((1.0, 2.0), 5), ((3.0, 4.0), 6)],dtype=[('x', [('a', '<f8'), ('b', '<f4')]), ('y', '<i4')])
data['x']Out[462]: array([(1.0, 2.0), (3.0, 4.0)],dtype=[('a', '<f8'), ('b', '<f4')])
data['y']Out[463]: array([5, 6])
data['x']['a']Out[464]: array([ 1., 3.])

12.12 values[: : -1] 返回一个反序的列表
arr = randn(3, 5)arrarray([[-0.1566, 0.6461, -0.1385, 0.4751, 0.2539],[ 0.279 , 0.9882, 0.7844, 0.9926, -0.4806],[ 0.5209, -0.8445, -1.4064, 1.5643, 0.178 ]])
arr.sort(axis=1)arr输出:Out[471]: array([[-0.1566, -0.1385, 0.2539, 0.4751, 0.6461],[-0.4806, 0.279 , 0.7844, 0.9882, 0.9926],[-1.4064, -0.8445, 0.178 , 0.5209, 1.5643]])
arr[:, ::-1]输出:arr[:, ::-1]Out[472]: array([[ 0.6461, 0.4751, 0.2539, -0.1385, -0.1566],[ 0.9926, 0.9882, 0.7844, 0.279 , -0.4806],[ 1.5643, 0.5209, 0.178 , -0.8445, -1.4064]])
12.13 间接排序: argsort 和lexsort
array.sort() 得到正确排序时,对应的元素位置
a = np.array([50, 5, 10, 30, 20])indexer = a.argsort()indexera[indexer]
输出:indexerOut[479]: array([1, 2, 4, 3, 0], dtype=int64)#红色部分为序列号#a[1]=5, a[2]=10, a[4]=20, a[3]=30, a[0]=50
a[indexer]Out[480]: array([ 5, 10, 20, 30, 50])
numpy.lexsort((x,y)):与argsort类似,一次性对元组进行间接排序(字典序)first_name = np.array(['Bob', 'Jane', 'Steve', 'Bill', 'Barbara'])last_name = np.array(['Jones', 'Arnold', 'Arnold', 'Jones', 'Walters'])sorter = np.lexsort((first_name, last_name))zip(last_name[sorter], first_name[sorter])#先对last_name进行排序,在last_name相同的情况下,对于first_name进行排序
输出:sorterOut[482]: array([1, 2, 3, 0, 4], dtype=int64)
zip(last_name[sorter], first_name[sorter])
Out[483]: [('Arnold', 'Jane'),('Arnold', 'Steve'),('Jones', 'Bill'),('Jones', 'Bob'),('Walters', 'Barbara')]


12.14 python中的排序算法quicksortmergesortheapsort示例:values = np.array(['2:first', '2:second', '1:first', '1:second', '1:third'])key = np.array([2, 2, 1, 1, 1])indexer = key.argsort(kind='mergesort')indexervalues.take(indexer)
12.15 numpy.searchedsorted: 在有序数组中查找元素
arr = np.array([0, 0, 0, 1, 1, 1, 1])arr.searchsorted([0, 1])#Out[486]: array([0, 3], dtype=int64)
arr.searchsorted([0, 1], side='right')Out[485]: array([3, 7], dtype=int64)
12.16 向量积
yOut[487]: array([[ 8.8277],[ 3.8222],[-1.1428],[ 2.0441]])
yT x y 表达为np.dot(y.T, np.dot(X, y))
12.17 Numpy的matrix
array直接转化为matrix类型
Xm = np.matrix(x)
Xm.T转置
ym.T*Xm*ym #星号(*)直接就是矩阵乘法
Xm.I#求逆矩阵
12.18 numpy.memmap 内存映像文件
>>>data= np.arange(12, dtype='float32')>>>data.resize((3,4))This example uses a temporary file so that doctest doesn’t write files to your directory. You would use a ‘normal’ filename.>>>>>>fromtempfileimport mkdtemp>>>importos.pathaspath>>>filename= path.join(mkdtemp(),'newfile.dat')Create a memmap with dtype and shape that matches our data:>>>>>>fp= np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))>>>fpmemmap([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], dtype=float32)Write data to memmap array:>>>>>>fp[:]= data[:]>>>fpmemmap([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32)>>>>>>fp.filename== path.abspath(filename)TrueDeletion flushes memory changes to disk before removing the object:>>>>>>del fpLoad the memmap and verify data was stored:>>>>>>newfp= np.memmap(filename, dtype='float32', mode='r', shape=(3,4))>>>newfpmemmap([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32)Read-only memmap:>>>>>>fpr= np.memmap(filename, dtype='float32', mode='r', shape=(3,4))>>>fpr.flags.writeableFalseCopy-on-write memmap:>>>>>>fpc= np.memmap(filename, dtype='float32', mode='c', shape=(3,4))>>>fpc.flags.writeableTrueIt’s possible to assign to copy-on-write array, but values are only written into the memory copy of the array, and not written to disk:>>>>>>fpcmemmap([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32)>>>fpc[0,:]=0>>>fpcmemmap([[ 0., 0., 0., 0.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32)File on disk is unchanged:>>>>>>fprmemmap([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.]], dtype=float32)Offset into a memmap:>>>>>>fpo= np.memmap(filename, dtype='float32', mode='r', offset=16)>>>fpomemmap([ 4., 5., 6., 7., 8., 9., 10., 11.], dtype=float32)Attributes
filename (str) Path to the mapped file.
offset (int) Offset position in the file.
mode (str) File mode.

第十四章 机器学习实战
14.1 operator.itemgetter()b = sorted(a, key = operator.itemgetter(1))#使用a的元素--元组的第二个元素进行排序a=[('b',2),('a',1),('c',0)]
operator.itemgetter函数operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子。
a = [1,2,3] >>> b=operator.itemgetter(1) //定义函数b,获取对象的第1个域的值>>> b(a) 2 >>> b=operator.itemgetter(1,0) //定义函数b,获取对象的第1个域和第0个的值>>> b(a) (2, 1)
要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。
sorted函数Python内置的排序函数sorted可以对list或者iterator进行排序,官网文档见:http://docs.python.org/2/library/functions.html?highlight=sorted#sorted,该函数原型为:
sorted(iterable[, cmp[, key[, reverse]]])
参数解释:
(1)iterable指定要排序的list或者iterable,不用多说;
(2)cmp为函数,指定排序时进行比较的函数,可以指定一个函数或者lambda函数,如:
students为类对象的list,没个成员有三个域,用sorted进行比较时可以自己定cmp函数,例如这里要通过比较第三个数据成员来排序,代码可以这样写:students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]sorted(students, key=lambda student : student[2])(3)key为函数,指定取待排序元素的哪一项进行排序,函数用上面的例子来说明,代码如下:sorted(students, key=lambda student : student[2])
key指定的lambda函数功能是去元素student的第三个域(即:student[2]),因此sorted排序时,会以students所有元素的第三个域来进行排序。
有了上面的operator.itemgetter函数,也可以用该函数来实现,例如要通过student的第三个域排序,可以这么写:sorted(students, key=operator.itemgetter(2))sorted函数也可以进行多级排序,例如要根据第二个域和第三个域进行排序,可以这么写:sorted(students, key=operator.itemgetter(1,2))
即先跟句第二个域排序,再根据第三个域排序。(4)reverse参数就不用多说了,是一个bool变量,表示升序还是降序排列,默认为false(升序排列),定义为True时将按降序排列。

-----
itemgetter来加速排序,并且可以减少代码的写作难度,我们来看看具体的例子,如何使用itemgetter:
  1. 首先装载一下operator模块
  1. 创建一个列表,列表由元组构成
  1. 使用itemgetter来进行排序,使用元组的第二个元素进行排序
  1. 使用元组的第一个元素进行排序
  1. 甚至我们可以先对元组的第2个元素进行排序,然后对第一个元素进行排序,形成多级排序。
  1. 当然,我们还可以使用reverse来进行逆序排列

14.2 dict.items() 和 dict.iteritems()
dict.items()返回的是一个完整的列表,而dict.iteritems()返回的是一个生成器(迭代器)。dict.items()返回列表list的所有列表项,形如这样的二元组list:[(key,value),(key,value),...],dict.iteritems()是generator, yield 2-tuple。相对来说,前者需要花费更多内存空间和时间,但访问某一项的时间较快(KEY)。后者花费很少的空间,通过next()不断取下一个值,但是将花费稍微多的时间来生成下一item。
字典items()操作方法:>>> x = {'title':'python web site','url':'www.iplaypy.com'}>>> x.items()[('url', 'www.iplaypy.com'), ('title', 'python web site')]从结果中可以看到,items()方法是将字典中的每个项分别做为元组,添加到一个列表中,形成了一个新的列表容器。如果有需要也可以将返回的结果赋值给新变量,这个新的变量就会是一个列表数据类型>>> a=x.items()>>> a[('url', 'www.iplaypy.com'), ('title', 'python web site')]>>> type(a)<type 'list'>
dict iteritems()操作方法>>> f = x.iteritems()>>> f<dictionary-itemiterator object at 0xb74d5e3c>>>> type(f)<type 'dictionary-itemiterator'> #字典项的迭代器>>> list(f)[('url', 'www.iplaypy.com'), ('title', 'python web site')]字典.iteritems()方法在需要迭代结果的时候使用最适合,而且它的工作效率非常的高。
dict.iteritems(), 类似于iteratorfor k,v in dict.iteritems():print k,v
是迭代器函数。可以在for循环内使用,单独使用的方法:iter = dict.iteritems()iter.next()
示例:
  1. #!/usr/bin/python
  2. dict={"a":"apple","b":"banana","o":"orange"}
  3. print"##########dict######################"
  4. foriindict:
  5. print"dict[%s]="%i,dict[i]
  6. print"###########items#####################"
  7. for(k,v)indict.items():
  8. print"dict[%s]="%k,v
  9. print"###########iteritems#################"
  10. fork,vindict.iteritems():
  11. print"dict[%s]="%k,v
  12. print"###########iterkeys,itervalues#######"
  13. fork,vinzip(dict.iterkeys(),dict.itervalues()):
  14. print"dict[%s]="%k,v
执行结果:
  1. ##########dict######################
  2. dict[a]=apple
  3. dict[b]=banana
  4. dict[o]=orange
  5. ###########items#####################
  6. dict[a]=apple
  7. dict[b]=banana
  8. dict[o]=orange
  9. ###########iteritems#################
  10. dict[a]=apple
  11. dict[b]=banana
  12. dict[o]=orange
  13. ###########iterkeys,itervalues#######
  14. dict[a]=apple
  15. dict[b]=banana
  16. dict[o]=orange

14.3importsyssys.path.append('lib/')importyourModule
这种方式可以,通过把相应的路径(例子中为lib/)加入系统路径,之后就可以按照正常方式import 了
14.4将x.py文件保存在一个文件夹,再在该文件夹下打开python。import x 可以自动摄取x.py文件中的函数

14.5 引入numpy下的所有方法
from numpy import *
14.6 tile()
tile函数位于python模块numpy.lib.shape_base中,他的功能是重复某个数组。比如tile(A,n),功能是将数组A重复n次,构成一个新的数组,我们还是使用具体的例子来说明问题:
  1. 先来引入numpy下的所有方法
  1. 我们创建一个a,如图下图,使用tile来创建b,注意看b的数据结构
  1. 假如我们输入一个元组(1,2),我们会得到一样的结果,与上面相同的b
  1. 当然,我们想要a变为一个二维数组,就要换一种重复的方式了。

14.7 array**2 -- 对每个元素开方
  1. >>>a=np.array([20,30,40,50])
  2. >>>b=np.arange(4)
  3. >>>b
  4. array([0,1,2,3])
  5. >>>c=a-b
  6. >>>c
  7. array([20,29,38,47])
  8. >>>b**2
  9. array([0,1,4,9])
  10. >>>10*np.sin(a)
  11. array([9.12945251,-9.88031624,7.4511316,-2.62374854])
  12. >>>a<35
  13. array([True,True,False,False],dtype=bool)

14.8numpy.ndarray.shape
ndarray.shapeTuple of array dimensions.
Notes
May be used to “reshape” the array, as long as this would not require a change in the total number of elements
Examples
>>>>>> x = np.array([1, 2, 3, 4])>>> x.shape(4,)>>> y = np.zeros((2, 3, 4))>>> y.shape(2, 3, 4)>>> y.shape = (3, 8)>>> yarray([[ 0., 0., 0., 0., 0., 0., 0., 0.],[ 0., 0., 0., 0., 0., 0., 0., 0.],[ 0., 0., 0., 0., 0., 0., 0., 0.]])>>> y.shape = (3, 6)Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: total size of new array must be unchangedTraceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: total size of new array must be unchanged
14.9 returnMat[index,:] = listFromLine[0:3]
#第index行的内容为listFromLine[0:3],如果不用index,那么变为每一行元素内容都为该list
14.10绘图的坐标轴或标题用中文显示
详情见文章 14.10
要使用中文注释,则需要在.py文件头一行,加上#-*- coding: utf-8 -*-绘图的坐标轴label或标题titile为中文,下面的三个红色框标注的方法。


14.11 ax.scatter(x,y, array_size, array_color)
import matplotlibimport matplotlib.pyplot as pltfrom matplotlib.font_manager import FontPropertiesimport numpy.random
font = FontProperties(fname='C:\Windows\Fonts\simfang.ttf',size=14)
fig = plt.figure()ax = fig.add_subplot(111) #参数111的意思是:将画布分割成1行1列,图像画在从左到右从上到下的第1块ax.scatter(datingDataMat[:,1], datingDataMat[:,2])#每一行,第2列和第3列的数据,datingDataMat[:,2] 类型为 array,1000行,每行元素为一个数字
plt.xlabel(u'玩视频游戏所耗时间百分比',fontproperties=font)plt.ylabel(u'每周所消费的冰淇淋公升数',fontproperties=font)plt.show()
ax.scatter(datingDataMat[:,1], datingDataMat[:,2], 150*array(random.randn(len(datingLabels))),15*array(datingLabels))#150*array(random.randn(len(datingLabels)))描述不同类的点中心彩色部分的大小,15*array(datingLabels)描述点的颜色
输出:ax.scatter(datingDataMat[:,1], datingDataMat[:,2], 150*array(random.randn(len(datingLabels))),15*array(datingLabels))
ax.scatter(datingDataMat[:,1], datingDataMat[:,2], 15*array(datingLabels),150*array(random.randn(len(datingLabels))))
14.12 更多关于 散点图plt.scatter 的技巧,如显示图片中的图
见文章14.12

14.13 matplotlib画图
http://matplotlib.org/api/pyplot_api.html
14.14array.min(0) #按照axis=0,即每列,求最小值array.max(1) #按照axis=1,按行,求最大值
14.15 listdir 列出文件夹中所有文件的名称
from os import listdirl1 = listdir(path) #type of l1 is list
示例:
x = listdir('C:/Users/310118430/OneDrive/Machine_Learning/Program/data/Ch02/digits/testDigits')
x[:10]Out[27]: ['0_0.txt','0_1.txt','0_10.txt','0_11.txt','0_12.txt','0_13.txt','0_14.txt','0_15.txt','0_16.txt','0_17.txt']
x = listdir('C:/Users/310118430/OneDrive/Machine_Learning/Program/data/Ch02/digits')
x[:10]Out[25]: ['testDigits', 'trainingDigits']
14.16 用python将图像二值化
见文章
14.17
python保存numpy数据:[python]view plaincopy
  1. numpy.savetxt("result.txt",numpy_data);




保存list数据:[python]view plaincopy
  1. file=open('data.txt','w')
  2. file.write(str(list_data));
  3. file.close()


第十五章 机器学习实战:决策树
15.1 del()
del用于list列表操作,删除一个或者连续几个元素
示例程序如下:>>> a = [-1, 3, 'aa', 85] # 定义一个list>>> a[-1, 3, 'aa', 85]>>> del a[0] # 删除第0个元素>>> a[3, 'aa', 85]>>> del a[2:4] # 删除从第2个元素开始,到第4个为止的元素。包括头不包括尾>>> a[3, 'aa']>>> del a # 删除整个list>>> aTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'a' is not defined
15.2Python对象引用和del删除引用1.首先介绍下python的对象引用1). python不允许程序员选择采用传值还是传引用。Python参数传递采用的肯定是“传对象引用”的方式。实际上,这种方式相当于传值和传引用的一种综合。如果函数收到的是一个可变对象(比如字典或者列表)的引用,就能修改对象的原始值——相当于通过“传引用”来传递对象。如果函数收到的是一个不可变对象(比如数字、字符或者元组)的引用,就不能直接修改原始对象——相当于通过“传值'来传递对象。2). 当人们复制列表或字典时,就复制了对象列表的引用同,如果改变引用的值,则修改了原始的参数。3). 为了简化内存管理,Python通过引用计数机制实现自动垃圾回收功能,Python中的每个对象都有一个引用计数,用来计数该对象在不同场所分别被引用了多少次。每当引用一次Python对象,相应的引用计数就增1,每当消毁一次Python对象,则相应的引用就减1,只有当引用计数为零时,才真正从内存中删除Python对象。
2. del 删除引用而不是删除对象,对象由自动垃圾回收机制删除看这个例子:>>> x = 1>>> del x>>> xTraceback (most recent call last):File "<pyshell#6>", line 1, in <module>xNameError: name 'x' is not defined>>> x = ['Hello','world']>>> y = x>>> y['Hello', 'world']>>> x['Hello', 'world']>>> del x>>> xTraceback (most recent call last):File "<pyshell#12>", line 1, in <module>xNameError: name 'x' is not defined>>> y['Hello', 'world']>>>

可以看到x和y指向同一个列表,但是删除x后,y并没有受到影响。这是为什么呢?The reason for this is that you only delete the name,not the list itself,In fact ,there is no way to delete values in python(and you don’t really need to because the python interpreter does it by itself whenever you don’t use the value anymore)举个例子,一个数据(比如例子中的列表),就是一个盒子,我们把它赋给一个变量x,就是好像把一个标签x贴到了盒子上,然后又贴上了y,用它们来代表这个数据,但是用del删除这个变量x就像是把标有x的标签给撕了,剩下了y的标签。再看一个例子:shoplist = ['apple', 'mango', 'carrot', 'banana']print ('The first item I will buy is', shoplist[0])olditem = shoplist[0]del shoplist[0] #del的是引用,而不是对象print ('I bought the',olditem)print ('My shopping list is now', shoplist)print(shoplist[0])结果为:The first item I will buy is appleI bought the appleMy shopping list is now ['mango', 'carrot', 'banana']mango
其他
15.3Python中的sorted函数以及operator.itemgetter函数operator.itemgetter函数operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子。a = [1,2,3]>>> b=operator.itemgetter(1) //定义函数b,获取对象的第1个域的值>>> b(a)2>>> b=operator.itemgetter(1,0) //定义函数b,获取对象的第1个域和第0个的值>>> b(a)(2, 1)要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。sorted函数Python内置的排序函数sorted可以对list或者iterator进行排序,官网文档见:http://docs.python.org/2/library/functions.html?highlight=sorted#sorted,该函数原型为:sorted(iterable[, cmp[, key[, reverse]]])参数解释:(1)iterable指定要排序的list或者iterable,不用多说;(2)cmp为函数,指定排序时进行比较的函数,可以指定一个函数或者lambda函数,如: students为类对象的list,没个成员有三个域,用sorted进行比较时可以自己定cmp函数,例如这里要通过比较第三个数据成员来排序,代码可以这样写: students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] sorted(students, key=lambda student : student[2])(3)key为函数,指定取待排序元素的哪一项进行排序,函数用上面的例子来说明,代码如下: sorted(students, key=lambda student : student[2]) key指定的lambda函数功能是去元素student的第三个域(即:student[2]),因此sorted排序时,会以students所有元素的第三个域来进行排序。有了上面的operator.itemgetter函数,也可以用该函数来实现,例如要通过student的第三个域排序,可以这么写:sorted(students, key=operator.itemgetter(2))sorted函数也可以进行多级排序,例如要根据第二个域和第三个域进行排序,可以这么写:sorted(students, key=operator.itemgetter(1,2))即先跟句第二个域排序,再根据第三个域排序。(4)reverse参数就不用多说了,是一个bool变量,表示升序还是降序排列,默认为false(升序排列),定义为True时将按降序排列。sorted函数更多的例子可以参考官网文档:https://wiki.python.org/moin/HowTo/Sorting/。
15.4 matplotlib annotate 添加标注http://matplotlib.org/users/annotations_intro.htmlhttp://matplotlib.org/examples/pylab_examples/annotation_demo.html
importnumpyasnpimportmatplotlib.pyplotaspltfig= plt.figure()ax= fig.add_subplot(111)t= np.arange(0.0,5.0,0.01)s= np.cos(2*np.pi*t)line,= ax.plot(t, s, lw=2)ax.annotate('local max', xy=(2,1), xytext=(3,1.5), arrowprops=dict(facecolor='black', shrink=0.05), )ax.set_ylim(-2,2)plt.show()(Source code,png,hires.png,pdf)importnumpyasnpimportmatplotlib.pyplotaspltfig= plt.figure()ax= fig.add_subplot(111, polar=True)r= np.arange(0,1,0.001)theta=2*2*np.pi*rline,= ax.plot(theta, r, color='#ee8d18', lw=3)ind=800thisr, thistheta= r[ind], theta[ind]ax.plot([thistheta], [thisr], 'o')ax.annotate('a polar annotation', xy=(thistheta, thisr), # theta, radius xytext=(0.05,0.05),# fraction, fraction textcoords='figure fraction', arrowprops=dict(facecolor='black', shrink=0.05), horizontalalignment='left', verticalalignment='bottom', )#xycoords = 'axes fraction': string that indicates what type of coordinates 'xy' isplt.show()(Source code,png,hires.png,pdf)http://www.tuicool.com/articles/fAjyuy
import matplotlib.pyplotas plt2import numpyas np34 x=np.linspace(-1,1,10)5 y=x**267 fig=plt.figure(figsize=(8,4))8 ax=plt.subplot(111)9 plt.plot(x,y)1011for i,(_x,_y)in enumerate(zip(x,y)):12 plt.text(_x,_y,i,color='red',fontsize=i+10)13 plt.text(0.5,0.8,'subplot words',color='blue',ha='center',transform=ax.trans Axes) 14 plt.figtext(0.1,0.92,'figure words',color='green')15 plt.annotate('buttom',xy=(0,0),xytext=(0.2,0.2),arrowprops=dict(facecolor='blue', shrink=0.05))16 plt.show()
前面1-10行很清楚啊。前面已经学习过了。11行表示i从0到N-1(N表示xy的个数),-x,-y从所给的数据中取10组出来。然后再每一个点的位置写上i。这个i 数字的大小是越来越大的。这个for i,(_x,_y) in enumerate(zip(x,y)):具体的用法不懂的可以参见http://blog.csdn.net/ikerpeng/article/details/19973321的第9个知识点。若是还要更加细致的了解在参见:http://www.saltycrane.com/blog/2008/04/how-to-use-pythons-enumerate-and-zip-to。后面13,14行讲的是子图和图像中输入文字。关于text()figtext(),具体的参见http://caoyaqiang.diandian.com/post/2013-02-03/40049144132。在通过annotate()函数画一个标注的箭头;其中的两个位置是箭头和箭尾的坐标,后面是颜色等信息。于是得到如下的结果:

15.5在.py文件中调用其他路径下的.py文件中的函数
将写好的.py文件作为模块,将其中的函数在其他.py文件或者脚本中使用。工具/原料
  • python开发包
方法/步骤
  1. 1. 在D:\python_code\try下创建文件fun.py
def f1(): print('hello world!') def f2(L): result = 0 for i in L: result += i return result def f3(x): print("old x = " + str(x)) x = 0 print("change to x = " + str(x)) value=100
  1. 如果没有在一个路径下要先将存放module的路径添加进来
from sys import pathpath.append(r'D:\python_code\try') #将存放module的路径添加进来import fun #引入模块
#注意此处的引用的文件名称不能用数字(例如:3_trees)开头,不能用常用语句(例如:try)开头,避免把文件命名为 try.py 或者 3_trees.py
from fun import f1,f2,f3 #引入模块中的函数fun.f1() #与下一个区别,用这个必须先用import引入模块f1()print f2([1,2,3,4,5])f3(20)print fun.value #打印引入模块的变量值
  1. 2.在同一路径下创建文件cal.py
import fun #引入模块from fun import f1,f2,f3 #引入模块中的函数fun.f1() #与下一个区别,用这个必须先用import引入模块f1() #需要时使用from…import…的方式引入才可以用print f2([1,2,3,4,5])f3(20)print fun.value #打印引入模块的变量值
  1. 3.运行结果:
hello world!hello world!15old x = 20change to x = 0100
  1. 4.在Console中调用。python import模块时, 是在sys.path里按顺序查找的。sys.path是一个列表,里面以字符串的形式存储了许多路径。使用fun.py文件中的函数需要先将他的文件路径放到sys.path中,用下面的方式:
from sys import pathpath.append(r'D:\python_code\try')然后import fun再调用fun模块下面的函数fun.f1()可以得到:hello world!或者fun.valueOut[5]: 100如果用from fun import f1,f2,f3的方式import,则可以直接用f1()hello world!但不能直接valuevalueTraceback (most recent call last): File "<ipython-input-17-756c412732c9>", line 1, in <module> valueNameError: name 'value' is not defined
15.6isinstance语法:isinstance(object,type)作用:来判断一个对象是否是一个已知的类型。其第一个参数(object)为对象,第二个参数(type)为类型名(int...)或类型名的一个列表((int,list,float)是一个列表)。其返回值为布尔型(True or flase)。若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。下面是两个例子:例一>>> a = 4>>> isinstance (a,int)True>>> isinstance (a,str)False>>> isinstance (a,(str,int,list))True例二>>> a = "b">>> isinstance(a,str)True>>> isinstance(a,int)False>>> isinstance(a,(int,list,float))False>>> isinstance(a,(int,list,float,str))True
15.7pickle
见文章15.7 pickle
15.8


更多相关文章

  1. 使用python如何在列表列表中找到元素,而关键元素是内部列表的元素
  2. 是否有一个类似于Python的“枚举”函数的Java ?
  3. 在python中创建指数函数。
  4. 对numpy数组的每n个元素求平均值
  5. 008 Python基本语法元素小结
  6. Python定义函数时,不同参数类型的传递
  7. Python语言特性之1:函数参数传递
  8. python题目——认识*与**,判断函数输出
  9. Tensorflow部分函数功能

随机推荐

  1. Android开发系列(一)
  2. android-Notification.Action
  3. android wifi状态机原理
  4. 更新Android SDK, 升级ADT遇到的问题总结
  5. ImageView的属性android:scaleType,即Imag
  6. launcher3时钟小部件
  7. Android TTS 支持中文
  8. 2020最新版Android一步一步教轻松通过Arc
  9. android使用滚动视图
  10. android UI跨线程操作