Python数据分析(二):Pandas库学习

一、Pandas简介

pandas是python的一个数据分析包,最初是被作为金融数据分析工具而开发出来的。pandas提供了大量快速便捷地处理数据的函数和方法,基本功能有以下几点:
1、具备按轴自动或显式数据对齐功能的数据机构
2、集成时间序列功能
3、既能处理时间序列数据也能处理非时间序列数据的数据结构
4、数学运算和约简(比如对某个轴求和)可以根据不同的元数据(轴编号)执行
5、灵活处理缺失数据
6、合并及其他出现在常见数据库(例如基于SQL的)的关系型运算
pandas有三种数据形式,分别是Series、DataFrame和索引对象。

二、Series

Series是一种类似于一维数组的对象,它是由一组数据(各种Numpy数据类型)以及一组与之相关的数据标签(即索引)组成。
Series的字符串变现形式为:索引在左边,值在右边。

from pandas import Series
print('用数组生成Series')
obj=Series([4,7,-5,3])#不指定的话从0开始
print(obj)
print(obj.values)
print(obj.index)
#输出结果
用数组生成Series
0    4
1    7
2   -5
3    3
dtype: int64
[ 4  7 -5  3]
RangeIndex(start=0, stop=4, step=1)

print('指定Series的index')
obj2=Series([4,7,-5,3],index=['d','b','a','c'])
print(obj2)
print(obj2.index)
print(obj2['a'])
#输出结果
指定Series的index
d    4
b    7
a   -5
c    3
dtype: int64
Index(['d', 'b', 'a', 'c'], dtype='object')
-5

obj2['d']=6
print(obj2[['c','a','d']])
#输出结果
c    3
a   -5
d    6
dtype: int64

print(obj2>0)
#输出结果
d     True
b     True
a    False
c     True
dtype: bool

print(obj2[obj2>0]) #找出大于0的元素
#输出结果
d    6
b    7
c    3
dtype: int64

print('b' in obj2)
print('e' in obj2)
#输出结果
True
False

print('使用字典生成Series')
sdata={'Ohio':45000,'Texas':71000,'Oregon':16000,'Utah':5000}
obj3=Series(sdata)
print(obj3)
#输出结果
使用字典生成Series
Ohio      45000
Texas     71000
Oregon    16000
Utah       5000
dtype: int64

print('使用字典生成Series,并额外指定index,不匹配部分为NaN')
states=['California','Ohio','Oregon','Texas']
obj4=Series(sdata,index=states)
print(obj4)
#输出结果
使用字典生成Series,并额外指定index,不匹配部分为NaN
California        NaN
Ohio          45000.0
Oregon        16000.0
Texas         71000.0
dtype: float64

print('Series相加,相同索引部分相加')
print(obj3+obj4)
#输出结果
Series相加,相同索引部分相加
California         NaN
Ohio           90000.0
Oregon         32000.0
Texas         142000.0
Utah               NaN
dtype: float64

print('指定Series及其索引的名字')
obj4.name='population'#数据命名为population
obj4.index.name='state'#索引命名为state
print(obj4)
#输出结果
指定Series及其索引的名字
state
California        NaN
Ohio          45000.0
Oregon        16000.0
Texas         71000.0
Name: population, dtype: float64

print('替换index')
obj.index=['Bob','Steve','Jeff','Ryan']
print(obj)
#输出结果
替换index
Bob      4
Steve    7
Jeff    -5
Ryan     3
dtype: int64

三、DataFrame

1、DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔值等)
2、DataFrame既有行索引也有列索引,它可以被看做由Series组成的字典(共用同一个索引)
3、可以输出给DataFrame构造器的数据

类型 说明
二维ndarray 数据矩阵,还可以传入行标和列标
由数组、列表或元组组成的字典 每个序列会生成DataFrame的一列,所有序列的长度必须相同
NumPy的结构化/记录数组 类似于“由数组组成的字典”
由Series组成的字典 每个Series会组成一列,如果没有显示指定索引,则各Series的索引会被合并成结果的行索引
由字典组成的字典 各内层字典会成为一列,键会被合并成结果的行索引,跟“由Series组成的字典”的情况一样
字典或Series的列表 各项将会成为DataFrame的一行,字典键或Series索引的并集将会成为DataFrame的列标
由列表或元组组成的列表 类似于“二维ndarray”
另一个DataFrame 该DataFrame的索引将会被沿用,除非显示指定了其他索引
NumPy的MaskedArray 类似于“二维ndarray”的情况,只是掩码值在结果DataFrame会变成NA/缺失值。
import numpy as np
from pandas import Series,DataFrame
print('用字典生成DataFrame,key为列的名字')
data={'state':['Ohio','Ohio','Ohio','Nevada','Nevada'],
     'year':[2000,2001,2002,2001,2002],
     'pop':[1.5,1.7,3.6,2.4,2.9]}
print(DataFrame(data))
print(DataFrame(data,columns=['year','state','pop']))#指定列的顺序
#输出结果
用字典生成DataFrame,key为列的名字
    state  year  pop
0    Ohio  2000  1.5
1    Ohio  2001  1.7
2    Ohio  2002  3.6
3  Nevada  2001  2.4
4  Nevada  2002  2.9
   year   state  pop
0  2000    Ohio  1.5
1  2001    Ohio  1.7
2  2002    Ohio  3.6
3  2001  Nevada  2.4
4  2002  Nevada  2.9

print('指定索引,在列中指定不存在的列,默认数据为NaN')
frame2=DataFrame(data,columns=['year','state','pop','debt'],
                index=['one','two','three','four','five'])
print(frame2)
#输出结果
指定索引,在列中指定不存在的列,默认数据为NaN
       year   state  pop debt
one    2000    Ohio  1.5  NaN
two    2001    Ohio  1.7  NaN
three  2002    Ohio  3.6  NaN
four   2001  Nevada  2.4  NaN
five   2002  Nevada  2.9  NaN

print(frame2['state'])
#输出结果
one        Ohio
two        Ohio
three      Ohio
four     Nevada
five     Nevada
Name: state, dtype: object

print(frame2.year)
print(frame2['year'])
#输出结果
one      2000
two      2001
three    2002
four     2001
five     2002
Name: year, dtype: int64
one      2000
two      2001
three    2002
four     2001
five     2002
Name: year, dtype: int64

print(frame2.loc['three']) #行索引
#输出结果
year     2002
state    Ohio
pop       3.6
debt      NaN
Name: three, dtype: object

frame2['debt']=16.5  #修改一整列
print(frame2)
#输出结果
       year   state  pop  debt
one    2000    Ohio  1.5  16.5
two    2001    Ohio  1.7  16.5
three  2002    Ohio  3.6  16.5
four   2001  Nevada  2.4  16.5
five   2002  Nevada  2.9  16.5

frame2.debt=np.arange(5)#用numpy数组修改元素
print(frame2)
#输出结果
       year   state  pop  debt
one    2000    Ohio  1.5     0
two    2001    Ohio  1.7     1
three  2002    Ohio  3.6     2
four   2001  Nevada  2.4     3
five   2002  Nevada  2.9     4

print('用Series指定要修改的索引及其对应的值,没有指定的默认数据用NaN')
val=Series([-1.2,-1.5,-1.7],index=['two','four','five'])
frame2['debt']=val
print(frame2)
#输出结果
用Series指定要修改的索引及其对应的值,没有指定的默认数据用NaN
       year   state  pop  debt
one    2000    Ohio  1.5   NaN
two    2001    Ohio  1.7  -1.2
three  2002    Ohio  3.6   NaN
four   2001  Nevada  2.4  -1.5
five   2002  Nevada  2.9  -1.7

print('赋值给新列')
frame2['eastern']=(frame2.state=='Ohio') #如果state等于Ohiow为True,不等于为False
print(frame2)
print(frame2.columns)
#输出结果
赋值给新列
       year   state  pop  debt  eastern
one    2000    Ohio  1.5   NaN     True
two    2001    Ohio  1.7  -1.2     True
three  2002    Ohio  3.6   NaN     True
four   2001  Nevada  2.4  -1.5    False
five   2002  Nevada  2.9  -1.7    False
Index(['year', 'state', 'pop', 'debt', 'eastern'], dtype='object')
print('DataFrame转置')
pop={'Nevada':{2001:2.4,2002:2.9},'Ohio':{2000:1.5,2001:1.7,2002:3.6}}
frame3=DataFrame(pop)
print(frame3)
print(frame3.T)
#输出结果
DataFrame转置
      Nevada  Ohio
2001     2.4   1.7
2002     2.9   3.6
2000     NaN   1.5
        2001  2002  2000
Nevada   2.4   2.9   NaN
Ohio     1.7   3.6   1.5

print('指定索引顺序,以及使用切片初始化数据')
print(DataFrame(pop,index=[2001,2002,2003]))
#输出结果
指定索引顺序,以及使用切片初始化数据
      Nevada  Ohio
2001     2.4   1.7
2002     2.9   3.6
2003     NaN   NaN

pdata={'Ohio':frame3['Ohio'][:-1],'Nevada':frame3['Nevada'][:2]}
print(DataFrame(pdata))
#输出结果
      Ohio  Nevada
2001   1.7     2.4
2002   3.6     2.9

print('指定索引和列的名称')
frame3.index.name='year'
frame3.columns.name='state'
print(frame3)
#输出结果
指定索引和列的名称
state  Nevada  Ohio
year               
2001      2.4   1.7
2002      2.9   3.6
2000      NaN   1.5

print(frame3.values)
#输出结果
[[2.4 1.7]
 [2.9 3.6]
 [nan 1.5]]

print(frame2.values)
#输出结果
[[2000 'Ohio' 1.5 nan True]
 [2001 'Ohio' 1.7 -1.2 True]
 [2002 'Ohio' 3.6 nan True]
 [2001 'Nevada' 2.4 -1.5 False]
 [2002 'Nevada' 2.9 -1.7 False]]

四、索引对象

1、pandas的索引对象负责管理轴标签和其他元数据(比如轴名称等)。构建Series或DataFrame时,所用到的任何数组或其他序列的标签都会被转换成index。
2、index对象是不可修改的(immutable),因此用户不能对其进行修改。不可修改性非常重要,因此这样才能使index对象在多个数据结构之间安全共享。

import numpy as np
import pandas as pd
import sys
from pandas import Series,DataFrame,Index
print('获取index')
obj=Series(range(3),index=['a','b','c'])
index=obj.index
print(index[1:])
try:
    index[1]='d'  #index对象read only
except:
    print(sys.exc_info()[0])
#输出结果
获取index
Index(['b', 'c'], dtype='object')
<class 'TypeError'>

print('使用index对象')
index=Index(np.arange(3))
obj2=Series([1.5,-2.5,0],index=index)
print(obj2)
print(obj2.index is index)
#输出结果
使用index对象
0    1.5
1   -2.5
2    0.0
dtype: float64
True

print('判断列和索引是否存在')
pop={'Nevada':{2001:2.4,2002:2.9},
    'Ohio':{2000:1.5,2001:1.7,2002:3.6}}
frame3=DataFrame(pop)
print('Ohio' in frame3.columns)
print('2003' in frame3.index)
#输出结果
判断列和索引是否存在
True
False

3、pandas中主要的index对象

类型 说明
index 最泛化的Index对象,将轴标签作为一个由Python对象组成的NumPy数组
int64Index 针对整数的特殊Index
MultiIndex "层次化"索引对象,表示单个轴上的多层索引。可以看做由原数组组成的数组
DatatimeIndex 存储纳秒级时间戳
PeriodIndex 针对Period数据的特殊Index

五、基本功能——重新索引

1、创建一个适应新索引的新对象,该Series的reindex将会根据新索引进行重排。如果某个索引值当前不存在,就引入缺失值。
2、对于时间序列这样的有序数据,重新索引时可能需要做一些插值处理。method选项即可达到此目的。
3、reindex函数的参数

类型 说明
index 用于索引的新序列。既可以是index实例,也可以是其他序列类型的python数据结构。index会被完全使用,就像没有任何复制一样
method 插值填充方式,ffill或bfill
fill_value 在重新索引过程中,需要引入缺失值时使用的替代值
limit 前向或后向填充时的最大填充量
level 在MultiIndex的指定级别上匹配简单索引,否则选取其子集
copy 默认为True,无论如何都复制。如果为False,则新旧相等就不复制。
import numpy as np
from pandas import DataFrame,Series
print('重新制定索引及顺序')
obj=Series([4.5,7.2,-5.3,3.6],index=['d','b','a','c'])
print(obj)
#输出结果
重新制定索引及顺序
d    4.5
b    7.2
a   -5.3
c    3.6
dtype: float64

obj2=obj.reindex(['a','b','d','c','e'])    #重新指定索引而不是改变索引本身
print(obj2)
#输出结果
a   -5.3
b    7.2
d    4.5
c    3.6
e    NaN
dtype: float64

print(obj.reindex(['a','b','d','c','e'],fill_value=0))#指定不存在的元素
#输出结果
a   -5.3
b    7.2
d    4.5
c    3.6
e    0.0
dtype: float64

print('重新指定索引并指定元素填充方法')
obj3=Series(['blue','purple','yellow'],index=[0,2,4])
print(obj3)
#输出结果
重新指定索引并指定填元素充方法
0      blue
2    purple
4    yellow
dtype: object

print(obj3.reindex(range(6),method='ffill'))#用前面一行的值去填充
#输出结果
0      blue
1      blue
2    purple
3    purple
4    yellow
5    yellow
dtype: object

print('对DataFrame重新指定索引')
frame=DataFrame(np.arange(9).reshape(3,3),
               index=['a','c','d'],
               columns=['Ohio','Texas','California'])
print(frame)
#输出结果
对DataFrame重新指定索引
   Ohio  Texas  California
a     0      1           2
c     3      4           5
d     6      7           8

frame2=frame.reindex(['a','b','c','d'])
print(frame2)
#输出结果
   Ohio  Texas  California
a   0.0    1.0         2.0
b   NaN    NaN         NaN
c   3.0    4.0         5.0
d   6.0    7.0         8.0

print('重新指定column')
states=['Texas','Utah','California']
print(frame.reindex(columns=states))
#输出结果
重新指定column
   Texas  Utah  California
a      1   NaN           2
c      4   NaN           5
d      7   NaN           8

print('对DataFrame重新指定索引并指定填充元素方法')
print(frame.reindex(index=['a','b','c','d'],columns=states).ffill())
print(frame.loc[['a','b','d','c'],states])
x=frame.reindex(index=['a','b','c','d'],columns=states).ffill()
print(x.drop('Utah',axis=1))
#输出结果
对DataFrame重新指定索引并指定填充元素方法
   Texas  Utah  California
a    1.0   NaN         2.0
b    1.0   NaN         2.0
c    4.0   NaN         5.0
d    7.0   NaN         8.0
   Texas  Utah  California
a    1.0   NaN         2.0
b    NaN   NaN         NaN
d    7.0   NaN         8.0
c    4.0   NaN         5.0
   Texas  California
a    1.0         2.0
b    1.0         2.0
c    4.0         5.0
d    7.0         8.0

六、基本功能——丢弃指定轴上的项

丢弃某条轴上的一个或多个项很简单,只要有一个索引数组或列表即可。由于需要执行一些数据整理和集合逻辑,所以drop方法返回的是一个在指定轴上删除了指定值的新对象

import numpy as np
from pandas import Series,DataFrame
print('Series根据索引删除元素')
obj=Series(np.arange(5),index=['a','b','c','d','e'])
new_obj=obj.drop('c')
print(new_obj)
#输出结果
Series根据索引删除元素
a    0
b    1
d    3
e    4
dtype: int64

print(obj.drop(['d','c']))
#输出结果
a    0
b    1
e    4
dtype: int64

print('DataFrame删除元素,可指定索引或列')
data=DataFrame(np.arange(16).reshape((4,4)),
              index=['Ohio','Colorado','Utah','New York'],
              columns=['one','two','three','four'])
print(data)
#输出结果
DataFrame删除元素,可指定索引或列
          one  two  three  four
Ohio        0    1      2     3
Colorado    4    5      6     7
Utah        8    9     10    11
New York   12   13     14    15

print(data.drop(['Colorado','Ohio']))#不指定直接删除行
#输出结果
          one  two  three  four
Utah        8    9     10    11
New York   12   13     14    15

print(data.drop('two',axis=1))
#输出结果
          one  three  four
Ohio        0      2     3
Colorado    4      6     7
Utah        8     10    11
New York   12     14    15

print(data.drop(['two','four'],axis=1))#原始数据data没有发生改变
#输出结果
          one  three
Ohio        0      2
Colorado    4      6
Utah        8     10
New York   12     14

七、基本功能——索引、选取和过滤

1、Series索引(obj[...])的工作方式类似与NumPy数组的索引,只不过Series索引值不只是整数
2、利用标签的切片运算与普通的Python切片运算不同,其末端是包含的(inclusive)
3、对DataFrame进行索引其实就是获取一个或多个列
4、为了在DataFrame的行上进行标签索引,引入了专门的索引字段ix(python3版本即将弃用)
注:
loc——通过行标签索引行数据
iloc——通过行号索引行数据
ix——通过行标签或者行号索引行数据(基于loc和iloc 的混合)

import numpy as np
from pandas import Series,DataFrame
print('Series的索引,默认数字索引可以工作')
obj=Series(np.arange(4),index=['a','b','c','d'])
print(obj['b'])
print(obj[3])
print(obj[[3]])#默认的数字数组索引
print(obj[[1,3]])#花式索引
print(obj[obj<2])
#输出结果
Series的索引,默认数字索引可以工作
1
3
d    3
dtype: int64
b    1
d    3
dtype: int64
a    0
b    1
dtype: int64

print('Series的数组切片')
print(obj['b':'c'])#闭区间,非数字索引是闭区间
obj['b':'c']=5
print(obj)
#输出结果
Series的数组切片
b    5
c    5
dtype: int64
a    0
b    5
c    5
d    3
dtype: int64

print('DataFrame的索引')
data=DataFrame(np.arange(16).reshape((4,4)),index=['Ohio','Colorado','Utah','New York'],
              columns=['one','two','three','four'])
print(data)
print(data['two'])#打印列
print(data[['three','one']])
print(data[:2]) #前两行
print(data.ix['Colorado',['two','three']])#指定索引和列
print(data.ix[['Colorado','Utah'],[3,0,1]])
print(data.ix[2])#打印第2行(从0开始)
print(data.ix[:'Utah','two'])#从开始到Utah,第2列
#输出结果
DataFrame的索引
          one  two  three  four
Ohio        0    1      2     3
Colorado    4    5      6     7
Utah        8    9     10    11
New York   12   13     14    15
Ohio         1
Colorado     5
Utah         9
New York    13
Name: two, dtype: int64
          three  one
Ohio          2    0
Colorado      6    4
Utah         10    8
New York     14   12
          one  two  three  four
Ohio        0    1      2     3
Colorado    4    5      6     7
two      5
three    6
Name: Colorado, dtype: int64
          four  one  two
Colorado     7    4    5
Utah        11    8    9
one       8
two       9
three    10
four     11
Name: Utah, dtype: int64
Ohio        1
Colorado    5
Utah        9
Name: two, dtype: int64

print('根据条件选择')
print(data[data.three>5])
print(data<5)#打印True或False
data[data<5]=0
print(data)
#输出结果
根据条件选择
          one  two  three  four
Colorado    4    5      6     7
Utah        8    9     10    11
New York   12   13     14    15
            one    two  three   four
Ohio       True   True   True   True
Colorado   True  False  False  False
Utah      False  False  False  False
New York  False  False  False  False
          one  two  three  four
Ohio        0    0      0     0
Colorado    0    5      6     7
Utah        8    9     10    11
New York   12   13     14    15

八、基本功能——算术运算和数据对齐

1、对不同的索引对象进行算数运算
2、自动数据对齐在不重叠的索引处引入了NA值,缺失值会在算术运算过程中传播
3、对于DataFrame,对齐操作会同时发生在行和列上
4、fill_value参数
5、DataFrame和Series之间的运算

import numpy as np
from pandas import Series,DataFrame
print('加法')
s1=Series([7.3,-2.5,3.4,1.5],index=['a','c','d','e'])
s2=Series([-2.1,3.6,-1.5,4,3.1],index=['a','c','e','f','g'])
print(s1)
print(s2)
print(s1+s2)
#输出结果
加法
a    7.3
c   -2.5
d    3.4
e    1.5
dtype: float64
a   -2.1
c    3.6
e   -1.5
f    4.0
g    3.1
dtype: float64
a    5.2
c    1.1
d    NaN
e    0.0
f    NaN
g    NaN
dtype: float64

print('DataFrame加法,索引和列都必须匹配')
df1=DataFrame(np.arange(9).reshape((3,3)),
             columns=list('bcd'),
             index=['Ohio','Texas','Colorado'])
df2=DataFrame(np.arange(12).reshape((4,3)),
             columns=list('bde'),
             index=['Utah','Ohio','Texas','Oregon'])
print(df1)
print(df2)
print(df1+df2)
#输出结果
DataFrame加法,索引和列都必须匹配
          b  c  d
Ohio      0  1  2
Texas     3  4  5
Colorado  6  7  8
        b   d   e
Utah    0   1   2
Ohio    3   4   5
Texas   6   7   8
Oregon  9  10  11
            b   c     d   e
Colorado  NaN NaN   NaN NaN
Ohio      3.0 NaN   6.0 NaN
Oregon    NaN NaN   NaN NaN
Texas     9.0 NaN  12.0 NaN
Utah      NaN NaN   NaN NaN

print('数据填充')
df1=DataFrame(np.arange(12).reshape((3,4)),columns=list('abcd'))
df2=DataFrame(np.arange(20).reshape((4,5)),columns=list('abcde'))
print(df1)
print(df2)
print(df1.add(df2,fill_value=0))
print(df1.reindex(columns=df2.columns,fill_value=0))
#输出结果
数据填充
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
    a   b   c   d   e
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19
      a     b     c     d     e
0   0.0   2.0   4.0   6.0   4.0
1   9.0  11.0  13.0  15.0   9.0
2  18.0  20.0  22.0  24.0  14.0
3  15.0  16.0  17.0  18.0  19.0
   a  b   c   d  e
0  0  1   2   3  0
1  4  5   6   7  0
2  8  9  10  11  0

print('DataFrame与Series之间的操作')
arr=np.arange(12).reshape((3,4))
print(arr)
print(arr[0])
print(arr-arr[0])
frame=DataFrame(np.arange(12).reshape((4,3)),
               columns=list('bde'),
               index=['Utah','Ohio','Texas','Oregon'])
series=frame.ix[0]
print(frame)
print(series)
print(frame-series)
series2=Series(range(3),index=list('bef'))#range(3)=[0,3],返回的是一个可迭代的对象,而不是列表
print(frame+series2)
series3=frame['d']
print(frame.sub(series3,axis=0))#按列减
#输出结果
DataFrame与Series之间的操作
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[0 1 2 3]
[[0 0 0 0]
 [4 4 4 4]
 [8 8 8 8]]
        b   d   e
Utah    0   1   2
Ohio    3   4   5
Texas   6   7   8
Oregon  9  10  11
b    0
d    1
e    2
Name: Utah, dtype: int64
        b  d  e
Utah    0  0  0
Ohio    3  3  3
Texas   6  6  6
Oregon  9  9  9
          b   d     e   f
Utah    0.0 NaN   3.0 NaN
Ohio    3.0 NaN   6.0 NaN
Texas   6.0 NaN   9.0 NaN
Oregon  9.0 NaN  12.0 NaN
        b  d  e
Utah   -1  0  1
Ohio   -1  0  1
Texas  -1  0  1
Oregon -1  0  1

九、基本功能——函数应用和映射

1、numpy的ufuncs(元素级数组方法)
2、DataFrame的apply方法
3、对象的applymap方法(因为Series有一个应用于元素级的map方法

import numpy as np
from pandas import Series,DataFrame
print('函数')
frame=DataFrame(np.random.randn(4,3),
               columns=list('bde'),
               index=['Utah','Ohio','Texas','Oregon'])
print(frame)
print(np.abs(frame))
#输出结果
函数
               b         d         e
Utah    0.446524 -0.045516 -0.745873
Ohio    0.425788  0.198789 -0.326030
Texas  -1.374720  0.941039  1.248235
Oregon  0.732467 -0.823564 -1.864570
               b         d         e
Utah    0.446524  0.045516  0.745873
Ohio    0.425788  0.198789  0.326030
Texas   1.374720  0.941039  1.248235
Oregon  0.732467  0.823564  1.864570

print('lambda以及应用')
f=lambda x:x.max()-x.min()
print(frame.apply(f))#按列操作,每列上的最大值减去最小值
print(frame.apply(f,axis=1))#按行操作
def f(x):#不使用匿名函数
    return Series([x.min(),x.max()],index=['min','max'])
print(frame.apply(f))
#输出结果
lamnda以及应用
b    2.107187
d    1.764603
e    3.112805
dtype: float64
Utah      1.192397
Ohio      0.751818
Texas     2.622955
Oregon    2.597037
dtype: float64
            b         d         e
min -1.374720 -0.823564 -1.864570
max  0.732467  0.941039  1.248235

print('applymap和map')
_format=lambda x:'%.2f' % x   #取x的前两位,Python的一种表达式   %前面对应的是字符串,后面对应参数
print(frame.applymap(_format))#每一个元素
print(frame['e'].map(_format))#某一列的元素,相当于Series


#DataFrame调用applymap函数作用到每个元素上
#Series调用map作用到每个元素上
#输出结果
applymap和map
            b      d      e
Utah     0.45  -0.05  -0.75
Ohio     0.43   0.20  -0.33
Texas   -1.37   0.94   1.25
Oregon   0.73  -0.82  -1.86
Utah      -0.75
Ohio      -0.33
Texas      1.25
Oregon    -1.86
Name: e, dtype: object

十、基本功能——排序和排名

1、对行或列索引进行排序
2、对于DataFrame,根据任意一个轴上的索引进行排序
3、可以指定升序降序
4、按值排序
5、对于DataFrame,可以指定按值排序的列
6、rank函数

import numpy as np
from pandas import Series,DataFrame
print('根据索引排序,对于DataFrame可以指定轴')
obj=Series(range(4),index=['d','a','b','c'])
print(obj.sort_index())
#输出结果
根据索引排序,对于DataFrame可以指定轴
a    1
b    2
c    3
d    0
dtype: int64

frame=DataFrame(np.arange(8).reshape((2,4)),
               index=['three','one'],
               columns=list('dabc'))
print(frame.sort_index())
print(frame.sort_index(axis=1))

print(frame.sort_index(axis=1,ascending=False))#降序
#输出结果
       d  a  b  c
one    4  5  6  7
three  0  1  2  3
       a  b  c  d
three  1  2  3  0
one    5  6  7  4
       d  c  b  a
three  0  3  2  1
one    4  7  6  5

print('根据值排序')
obj=Series([4,7,-3,2])
print(obj.sort_values())#order已淘汰
#输出结果
根据值排序
2   -3
3    2
0    4
1    7
dtype: int64

print('DataFrame指定列排序')
frame=DataFrame({'b':[4,7,-3,2],'a':[0,1,0,1]})
print(frame)
print(frame.sort_values(by='b'))#sort_index(by=...)已淘汰
print(frame.sort_values(by=['a','b']))#先按列a排序,再按列b排序
#输出结果
DataFrame指定列排序
   b  a
0  4  0
1  7  1
2 -3  0
3  2  1
   b  a
2 -3  0
3  2  1
0  4  0
1  7  1
   b  a
2 -3  0
0  4  0
3  2  1
1  7  1

print('rank,求排名的平均位置(从1开始)')
obj=Series([7,-5,7,4,2,0,4])
#对应排名:-5(1),0(2),2(3),4(4),4(5),7(6),7(7)
print(obj.rank())
#输出结果
rank,求排名的平均位置(从1开始)
0    6.5
1    1.0
2    6.5
3    4.5
4    3.0
5    2.0
6    4.5
dtype: float64

print(obj.rank(method='first'))#取第一次出现,不求平均值
#输出结果
0    6.0
1    1.0
2    7.0
3    4.0
4    3.0
5    2.0
6    5.0
dtype: float64

print(obj.rank(ascending =False,method='max'))#不平均排名,降序排名,并且按照相同数字使用最大排名进行统一排名
#7(1),7(2),4,(3),4(4),2(5),0(6),-5(7)
#输出结果
0    2.0
1    7.0
2    2.0
3    4.0
4    5.0
5    6.0
6    4.0
dtype: float64

frame=DataFrame({'b':[4.3,7,-3,2],
                'a':[0,1,0,1],
                'c':[-2,5,8,-2.5]})
print(frame)
print(frame.rank(axis=1))#按行rank,以第一行为例,[4.3,0,-2.0]=>[-2.0(1),0(2),4.3(3)]=>[3.0,2.0,1.0]
#输出结果
     b  a    c
0  4.3  0 -2.0
1  7.0  1  5.0
2 -3.0  0  8.0
3  2.0  1 -2.5
     b    a    c
0  3.0  2.0  1.0
1  3.0  1.0  2.0
2  1.0  2.0  3.0
3  3.0  2.0  1.0

十一、基本功能——带有重复值的索引

对于重复索引,返回Series,对应单个值的索引则返回标量

import numpy as np
from pandas import Series,DataFrame
print('重复的索引')
obj=Series(range(5),index=['a','a','b','b','c'])
print(obj.index.is_unique)#判断索引是否唯一
print(type(obj['a']))
print(obj['a'].ix[0],obj['a'].ix[1])
# ,obj.a[1]
#输出结果
重复的索引
False
<class 'pandas.core.series.Series'>
0 1

df=DataFrame(np.random.randn(4,3),index=['a','a','b','b'])
print(df)
print(df.loc['b'].iloc[0])
print(df.loc['b'].iloc[1])
#输出结果
          0         1         2
a  0.155635 -0.099546  0.112265
a -0.918338  0.707659  0.263030
b -1.075503  0.902052  0.254616
b -0.245483 -0.058749  1.182611
0   -1.075503
1    0.902052
2    0.254616
Name: b, dtype: float64
0   -0.245483
1   -0.058749
2    1.182611
Name: b, dtype: float64

十二、汇总和计算描述统计

1、常用方法选项

类型 说明
axis 指定轴,DataFrame的行用0,列用1.
skipna 排除缺失值,默认值为True
level 如果轴是层次化索引的(即MultiIndex),则根据level选取分组

2、常用描述和汇总统计函数

类型 说明
count 非NA值的数量
describe 针对Series或各DataFrames列计算汇总统计
min,max 计算最小值和最大值
argmin,argmax 计算能够获取到最小值和最大值的索引位置(整数)
idxmin,idxmax 计算能够获取到最小值和最大值的索引值
sum 值的总和
mean 值的平均数
median 值的算数中位数
mad 根据平均值计算平均绝对离差
var 样本值的方差
std 样本值的标准差
skew 样本值的偏差(三阶矩)
kurt 样本值的偏差(四阶矩)
cumsum 样本值的累积和
cummin,cummax 样本值的累计最大值和累计最小值
cumprod 样本值的累计积
diff 计算一阶差分
pct_change 计算百分数变化

3、唯一值以及成员资格

类型 说明
is_in 计算一个表示“Series各值是否包含于传入的值序列中”的布尔型数组
unique 计算Series中的唯一值数组,按发现的顺序返回
value_counts 返回一个Series,其索引为唯一值,其值为频率,按计数值降序排列

4、处理缺失值
前面在例题中已经讲过了,后面还会出一期专门讲解一下如何处理缺失值的问题。
5、NA处理方法

类型 说明
dropna 根据各标签的值中是否存在缺少数据对轴标签进行过滤,可通过阈值调节对缺失值的容忍度
fillna 用指定值或插值方法(如ffill或bfill)填充缺失数据
isnull 返回一个含有布尔值的对象
notnull isnull的否定式
import numpy as np
from pandas import Series,DataFrame
print('求和')
df=DataFrame([[1.4,np.nan],[7.1,-4.5],[np.nan,np.nan],[0.75,-1.3]],
            index=['a','b','c','d'],
            columns=['one','two'])
print(df)
print(df.sum())#按列求和
print(df.sum(axis=1))#按行求和
#输出结果

求和
    one  two
a  1.40  NaN
b  7.10 -4.5
c   NaN  NaN
d  0.75 -1.3
one    9.25
two   -5.80
dtype: float64
a    1.40
b    2.60
c    0.00
d   -0.55
dtype: float64

print('平均数')
print(df.mean(axis=1,skipna=False))#按行
print(df.mean(axis=1))
#输出结果
平均数
a      NaN
b    1.300
c      NaN
d   -0.275
dtype: float64
a    1.400
b    1.300
c      NaN
d   -0.275
dtype: float64

print('其他')
print(df.idxmax())
print(df.cumsum())#按行累计
print(df.describe())
obj=Series(['a','a','b','c']*4)
print(obj.describe())
#输出结果
其他
one    b
two    d
dtype: object
    one  two
a  1.40  NaN
b  8.50 -4.5
c   NaN  NaN
d  9.25 -5.8
            one       two
count  3.000000  2.000000
mean   3.083333 -2.900000
std    3.493685  2.262742
min    0.750000 -4.500000
25%    1.075000 -3.700000
50%    1.400000 -2.900000
75%    4.250000 -2.100000
max    7.100000 -1.300000
count     16
unique     3
top        a
freq       8
dtype: object

十三、层次化索引

1、能在一个轴上拥有多个(两个以上)索引级别。抽象的说,它使你能以低纬度的形式处理高纬度数据
2、通过stack和unstack变换DataFrame

import numpy as np
from pandas import Series,DataFrame,MultiIndex
print('Series的层次索引')
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]])
print(data)
#输出结果
Series的层次索引
a  1    1.726844
   2    0.513376
   3   -1.901820
b  1    1.433962
   2    1.784395
   3   -0.109921
c  1   -0.235029
   2   -0.475485
d  2   -0.528125
   3   -0.076163
dtype: float64

print(data.index)
#输出结果
MultiIndex([('a', 1),
            ('a', 2),
            ('a', 3),
            ('b', 1),
            ('b', 2),
            ('b', 3),
            ('c', 1),
            ('c', 2),
            ('d', 2),
            ('d', 3)],
           )

print(data.b)
#输出结果
1    1.433962
2    1.784395
3   -0.109921
dtype: float64

print(data['b':'c'])
#输出结果
b  1    1.433962
   2    1.784395
   3   -0.109921
c  1   -0.235029
   2   -0.475485
dtype: float64

print(data[:2])
#输出结果
a  1    1.726844
   2    0.513376
dtype: float64

print(data.unstack())
#输出结果
          1         2         3
a  1.726844  0.513376 -1.901820
b  1.433962  1.784395 -0.109921
c -0.235029 -0.475485       NaN
d       NaN -0.528125 -0.076163

print(data.unstack().stack())
#输出结果
a  1    1.726844
   2    0.513376
   3   -1.901820
b  1    1.433962
   2    1.784395
   3   -0.109921
c  1   -0.235029
   2   -0.475485
d  2   -0.528125
   3   -0.076163
dtype: float64

print('DataFrame的层次索引')
frame=DataFrame(np.arange(12).reshape((4,3)),
               index=[['a','a','b','b'],[1,2,1,2]],
               columns=[['Ohio','Ohio','Colorado'],
                       ['Green','Red','Green']])
print(frame)
#输出结果
DataFrame的层次索引
     Ohio     Colorado
    Green Red    Green
a 1     0   1        2
  2     3   4        5
b 1     6   7        8
  2     9  10       11

frame.index.names=['key1','key2']
frame.columns.names=['state','color']
print(frame)
#输出结果
state      Ohio     Colorado
color     Green Red    Green
key1 key2                   
a    1        0   1        2
     2        3   4        5
b    1        6   7        8
     2        9  10       11

print(frame.index)
#输出结果
MultiIndex([('a', 1),
            ('a', 2),
            ('b', 1),
            ('b', 2)],
           names=['key1', 'key2'])

print(frame.columns)
#输出结果
MultiIndex([(    'Ohio', 'Green'),
            (    'Ohio',   'Red'),
            ('Colorado', 'Green')],
           names=['state', 'color'])

print(frame.loc['a',1])
#输出结果
state     color
Ohio      Green    0
          Red      1
Colorado  Green    2
Name: (a, 1), dtype: int64

print(frame.loc['a',2]['Colorado'])
#输出结果
color
Green    5
Name: (a, 2), dtype: int64

print(frame.loc['a',2]['Ohio']['Red'])
#输出结果
4

3、索引交换

import numpy as np
from pandas import Series,DataFrame
print('索引层级交换')
frame=DataFrame(np.arange(12).reshape((4,3)),
               index=[['a','a','b','b'],[1,2,1,2]],
               columns=[['Ohio','Ohio','Colorado'],['Green','Red','Green']])
frame.index.names=['key1','key2']
frame_swapped=frame.swaplevel('key1','key2')
print(frame_swapped)
print(frame_swapped.swaplevel(0,1))
#输出结果
索引层级交换
           Ohio     Colorado
          Green Red    Green
key2 key1                   
1    a        0   1        2
2    a        3   4        5
1    b        6   7        8
2    b        9  10       11
           Ohio     Colorado
          Green Red    Green
key1 key2                   
a    1        0   1        2
     2        3   4        5
b    1        6   7        8
     2        9  10       11

4、根据级别汇总统计

import numpy as np
from pandas import DataFrame
print('根据指定的key计算统计信息')
frame=DataFrame(np.arange(12).reshape((4,3)),
               index=[['a','a','b','b'],[1,2,1,2]],
               columns=[['Ohio','Ohio','Colorado'],['Green','Red','Green']])
frame.index.names=['key1','key2']
print(frame)
print(frame.sum(level='key2'))
print(frame.sum(level='key1'))
#输出结果
根据指定的key计算统计信息
           Ohio     Colorado
          Green Red    Green
key1 key2                   
a    1        0   1        2
     2        3   4        5
b    1        6   7        8
     2        9  10       11
      Ohio     Colorado
     Green Red    Green
key2                   
1        6   8       10
2       12  14       16
      Ohio     Colorado
     Green Red    Green
key1                   
a        3   5        7
b       15  17       19


print('使用列生成层次索引')
frame=DataFrame({'a':range(7),
                'b':range(7,0,-1),
                'c':['one','one','one','two','two','two','two'],
                'd':[0,1,2,0,1,2,3]})
print(frame)
print(frame.set_index(['c','d']))#把c/d列变成索引
print(frame.set_index(['c','d'],drop=False))#列依然保留
frame2=frame.set_index(['c','d'])
print(frame2.reset_index())
#输出结果
使用列生成层次索引
   a  b    c  d
0  0  7  one  0
1  1  6  one  1
2  2  5  one  2
3  3  4  two  0
4  4  3  two  1
5  5  2  two  2
6  6  1  two  3
       a  b
c   d      
one 0  0  7
    1  1  6
    2  2  5
two 0  3  4
    1  4  3
    2  5  2
    3  6  1
       a  b    c  d
c   d              
one 0  0  7  one  0
    1  1  6  one  1
    2  2  5  one  2
two 0  3  4  two  0
    1  4  3  two  1
    2  5  2  two  2
    3  6  1  two  3
     c  d  a  b
0  one  0  0  7
1  one  1  1  6
2  one  2  2  5
3  two  0  3  4
4  two  1  4  3
5  two  2  5  2
6  two  3  6  1

5、整数索引

import numpy as np
import sys
from pandas import Series,DataFrame
print('整数索引')
ser=Series(np.arange(3))
print(ser)
try:
    print(ser[-1]) #这里会有歧义
except:
    print(sys.exc_info()[0])
ser2=Series(np.arange(3),index=['a','b','c'])
print(ser2[-1])
ser3=Series(range(3),index=[-5,1,3])
print(ser3.iloc[2])#避免直接用[2]产生的歧义
print('对DataFrame使用整数索引')
frame=DataFrame(np.arange(6).reshape((3,2)),index=[2,0,1])
print(frame)
print(frame.iloc[0])
print(frame.iloc[:,1])
#输出结果
整数索引
0    0
1    1
2    2
dtype: int64
<class 'KeyError'>
2
2
对DataFrame使用整数索引
   0  1
2  0  1
0  2  3
1  4  5
0    0
1    1
Name: 2, dtype: int64
2    1
0    3
1    5
Name: 1, dtype: int64

好了,pandas库的学习到这里就结束了,下一篇我们利用学习的pandas知识,对股票数据进行一次实战分析。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271