[数据分析基础] 3. Pandas库

[数据分析基础] 3. Pandas库

pandas是Python第三方库,提供高性能易用数据类型和分析工具

import pandas as pd

Pandas基于NumPy实现,常与NumPy和Matplotlib一同使用

提供两个数据类型:Series, DataFrame。基于上述数据类型提供了各类操作:基本操作、运算操作、特征类操作、关联类操作

一、Series类型

Series类型由一组数据及与之相关的数据索引组成

In [5]: b=pd.Series([9,8,7,6],index=['a','b','c','d'])
 
In [6]: b
Out[6]:
a    9
b    8
c    7
d    6
dtype: int64
1. Series类型的创建

Series类型可以由如下类型创建:

  • Python列表,index与列表元素个数一致

  • 标量值,index表达Series类型的尺寸

  • Python字典,键值对中的“键”是索引,index从字典中进行选择操作

  • ndarray,索引和数据都可以通过ndarray类型创建

  • 其他函数,range()函数等

① 从标量值创建

In [7]: s=pd.Series(25,index=['a','b','c'])
 
In [8]: s
Out[8]:
a    25
b    25
c    25
dtype: int64

此方法创建时,不能省略index

② 从字典类型创建

In [9]: d=pd.Series({'a':9,'b':8,'c':7})
 
In [10]: d
Out[10]:
a    9
b    8
c    7
dtype: int64
 
In [11]: e=pd.Series({'a':9,'b':8,'c':7},index=['c','a','b','d'])
 
In [12]: e
Out[12]:
c    7.0
a    9.0
b    8.0
d    NaN
dtype: float64

index从字典中进行选择操作

③ 从ndarray类型创建

In [1]: import pandas as pd
 
In [2]: import numpy as np
 
In [3]: n=pd.Series(np.arange(5))
 
In [4]: n
Out[4]:
0    0
1    1
2    2
3    3
4    4
dtype: int32
 
In [5]: m=pd.Series(np.arange(5),index=np.arange(9,4,-1))
 
In [6]: n
Out[6]:
9    0
8    1
7    2
6    3
5    4
dtype: int32
2. Series类型的基本操作

Series类型包括index和values两部分,Series类型的操作类似ndarray类型和Python字典类型

.index 获得索引 .values 获得数据

自动索引和自定义索引并存(注意:两套索引并存,但不能混用)

In [7]: b=pd.Series([9,8,7,6],['a','b','c','d'])
 
In [8]: b
Out[8]:
a    9
b    8
c    7
d    6
dtype: int64
 
In [9]: b.index # .index获得索引
Out[9]: Index(['a', 'b', 'c', 'd'], dtype='object')
 
In [10]: b.values # .value 获得数据
Out[10]: array([9, 8, 7, 6], dtype=int64)
 
In [11]: b['b'] #自动索引
Out[11]: 8
 
In [12]: b[1] #自定义索引
Out[12]: 8
 
In [13]: b[['c','d',0]] #两套索引并存,但不能混用
Out[13]:
c    7.0
d    6.0
0    NaN
dtype: float64
 
In [14]: b[['c','d','a']]
Out[14]:
c    7
d    6
a    9
dtype: int64

Series类型的操作类似ndarray类型:

  • 索引方法相同,采用[]

  • NumPy中运算和操作可用于Series类型

  • 可以通过自定义索引的列表进行切片

  • 可以通过自动索引进行切片,如果存在自定义索引,则一同被切片

In [16]: b[3]
Out[16]: 6
 
In [17]: b[:3]
Out[17]:
a    9
b    8
c    7
dtype: int64
 
In [18]: b[b>b.median()]
Out[18]:
a    9
b    8
dtype: int64
 
In [19]: np.exp(b)
Out[19]:
a    8103.083928
b    2980.957987
c    1096.633158
d     403.428793
dtype: float64

Series类型的操作类似Python字典类型:

  • 通过自定义索引访问

  • 保留字in操作

  • 使用.get()方法

In [21]: b['b']
Out[21]: 8
 
In [22]: 'c' in b
Out[22]: True
 
In [23]: 0 in b
Out[23]: False
 
In [24]: b.get('f',100)
Out[24]: 100
 
In [25]: a=pd.Series([1,2,3],['c','d','e'])
 
In [26]: a+b #Series类型在运算中会自动对齐不同索引的数据
Out[26]:
a    NaN
b    NaN
c    8.0
d    8.0
e    NaN
dtype: float64
3. Series类型的name属性

Series对象和索引都可以有一个名字,存储在属性.name中

In [27]: b.name
 
In [28]: b.name='Series对象'
 
In [29]: b.index.name='索引列'
 
In [30]: b
Out[30]:
索引列
a    9
b    8
c    7
d    6
Name: Series对象, dtype: int64
4. Series类型的修改

Series对象可以随时修改并即刻生效

In [32]: b['a']=15
 
In [33]: b.name='Series'
 
In [34]: b
Out[34]:
索引列
a    15
b     8
c     7
d     6
Name: Series, dtype: int64
 
In [35]: b.name="New Series"
 
In [36]: b['b','c']=20
 
In [37]: b
Out[37]:
索引列
a    15
b    20
c    20
d     6
Name: New Series, dtype: int64

Series是一维的带“标签”的数组

Series基本操作类似ndarray和字典,根据索引对齐

二、DataFrame类型

DataFrame类型由共用相同索引的一组列组成。纵向索引叫index,axis = 0,横向缩索引叫column,axis = 1

DataFrame是一个表格型的数据类型,每列值类型可以不同,既有行索引、也有列索引,常用于表达二维数据,但可以表达多维数据

1. DataFrame类型的创建

DataFrame类型可以由如下类型创建:

  • 二维ndarray对象

  • 由一维ndarray、列表、字典、元组或Series构成的字典

  • Series类型

  • 其他的DataFrame类型

① 从二维ndarray对象创建

In [38]: d=pd.DataFrame(np.arange(10).reshape(2,5))
 
In [39]: d
Out[39]:
   0  1  2  3  4
0  0  1  2  3  4
1  5  6  7  8  9

最左侧为自动行索引;最顶端为自动列索引

② 从一维ndarray对象字典创建

In [40]: dt={'one':pd.Series([1,2,3],index=['a','b','c']),
    ...: 'two':pd.Series([9,8,7,6],index=['a','b','c','d'])}
 
In [41]: d=pd.DataFrame(dt)
 
In [42]: d
Out[42]:
   one  two
a  1.0    9
b  2.0    8
c  3.0    7
d  NaN    6
 
In [43]: pd.DataFrame(dt,index=['b','c','d'],columns=['two','three'])
Out[43]:
   two three
b    8   NaN
c    7   NaN
d    6   NaN

③ 从列表类型的字典创建

In [43]: pd.DataFrame(dt,index=['b','c','d'],columns=['two','three'])
Out[43]:
   two three
b    8   NaN
c    7   NaN
d    6   NaN
 
In [44]: dl={'one':[1,2,3,4],'two':[9,8,7,6]}
 
In [45]: d=pd.DataFrame(dl,index=['a','b','c','d'])
 
In [46]: d
Out[46]:
   one  two
a    1    9
b    2    8
c    3    7
d    4    6 

实例:

In [47]: dl={'城市':['北京','上海','广州','深圳','沈阳'],
    ...: '环比':[101.5,101.5,101.3,102.0,100.1],
    ...: '同比':[120.7,127.3,119.4,140.9,101.4],
    ...: '定基':[121.4,127.8,120.0,145.5,101.6]}
 
In [48]: d=pd.DataFrame(dl,index=['c1','c2','c3','c4','c5'])
 
In [49]: d
Out[49]:
    城市     环比     同比     定基
c1  北京  101.5  120.7  121.4
c2  上海  101.5  127.3  127.8
c3  广州  101.3  119.4  120.0
c4  深圳  102.0  140.9  145.5
c5  沈阳  100.1  101.4  101.6
 
In [50]: d.index
Out[50]: Index(['c1', 'c2', 'c3', 'c4', 'c5'], dtype='object')
 
In [51]: d.columns
Out[51]: Index(['城市', '环比', '同比', '定基'], dtype='object')
 
In [52]: d.values
Out[52]:
array([['北京', 101.5, 120.7, 121.4],
       ['上海', 101.5, 127.3, 127.8],
       ['广州', 101.3, 119.4, 120.0],
       ['深圳', 102.0, 140.9, 145.5],
       ['沈阳', 100.1, 101.4, 101.6]], dtype=object)
 
In [53]: d['同比']
Out[53]:
c1    120.7
c2    127.3
c3    119.4
c4    140.9
c5    101.4
Name: 同比, dtype: float64
 
In [54]: d.ix['c2']
Out[54]:
城市       上海
环比    101.5
同比    127.3
定基    127.8
Name: c2, dtype: object
 
In [55]: d['同比']['c2']
Out[55]: 127.3
三、Pandas库的数据类型操作

如何改变Series和DataFrame对象的结构?

  • 增加或重排:重新索引

  • 删除:drop

1. 重新索引

.reindex()能够改变或重排Series和DataFrame索引

In [2]: import pandas as pd
 
In [3]: dl={'城市':['北京','上海','广州','深圳','沈阳'],
   ...: '环比':[101.5,101.2,101.3,102.0,100.1],
   ...: '同比':[120.7,127.3,119.4,140.9,101.4],
   ...: '定基':[121.4,127.8,120.0,145.5,101.6]}
 
In [4]: d=pd.DataFrame(dl,index=['c1','c2','c3','c4','c5'])
 
In [5]: d
Out[5]:
    城市     环比     同比     定基
c1  北京  101.5  120.7  121.4
c2  上海  101.2  127.3  127.8
c3  广州  101.3  119.4  120.0
c4  深圳  102.0  140.9  145.5
c5  沈阳  100.1  101.4  101.6
 
In [6]: d=d.reindex(index=['c5','c4','c3','c2','c1'])
 
In [7]: d
Out[7]:
    城市     环比     同比     定基
c5  沈阳  100.1  101.4  101.6
c4  深圳  102.0  140.9  145.5
c3  广州  101.3  119.4  120.0
c2  上海  101.2  127.3  127.8
c1  北京  101.5  120.7  121.4
 
In [8]: d=d.reindex(columns=['城市','同比','环比','定基'])
 
In [9]: d
Out[9]:
    城市     同比     环比     定基
c5  沈阳  101.4  100.1  101.6
c4  深圳  140.9  102.0  145.5
c3  广州  119.4  101.3  120.0
c2  上海  127.3  101.2  127.8
c1  北京  120.7  101.5  121.4

.reindex(index=None, columns=None, …)的参数

参数说明
index,columns新的行列自定义索引
fill_value重新索引中,用于填充缺失位置的值
method填充方法,ffill当前值向前填充,bfill向后填充
limit最大填充量
copy默认True,生成新的对象,False时,新旧相等不复制
In [10]: newc=d.columns.insert(4,'新增')
 
In [11]: newd=d.reindex(columns=newc,fill_value=200)
 
In [12]: newd
Out[12]:
    城市     同比     环比     定基   新增
c5  沈阳  101.4  100.1  101.6  200
c4  深圳  140.9  102.0  145.5  200
c3  广州  119.4  101.3  120.0  200
c2  上海  127.3  101.2  127.8  200
c1  北京  120.7  101.5  121.4  200
索引类型

Series和DataFrame的索引是Index类型 Index对象是不可修改类型

In [13]: d.index
Out[13]: Index(['c5', 'c4', 'c3', 'c2', 'c1'], dtype='object')
 
In [14]: d.columns
Out[14]: Index(['城市', '同比', '环比', '定基'], dtype='object')
对索引类型的常用方法
方法说明
.append(idx)连接另一个Index对象,产生新的Index对象
.diff(idx)计算差集,产生新的Index对象
.intersection(idx)计算交集
.union(idx)计算并集
.delete(loc)删除loc位置处的元素
.insert(loc,e)在loc位置增加一个元素e
In [21]: nc=d.columns.delete(2)
 
In [22]: ni=d.index.insert(5,'c0')
 
In [40]: ni
Out[40]: Index(['c5', 'c4', 'c3', 'c2', 'c1', 'c0'], dtype='object')
 
In [42]: nd
Out[42]:
     城市     同比     定基
c5   沈阳  101.4  101.6
c4   深圳  140.9  145.5
c3   广州  119.4  120.0
c2   上海  127.3  127.8
c1   北京  120.7  121.4
c0  NaN    NaN    NaN
2. 删除指定索引对象

.drop()能够删除Series和DataFrame指定行或列索引

实例:(可以看出drop()是不改变d的值的)

In [45]: a=pd.Series([9,8,7,6],index=['a','b','c','d'])
 
In [46]: a
Out[46]:
a    9
b    8
c    7
d    6
dtype: int64
 
In [47]: a.drop(['b','c'])
Out[47]:
a    9
d    6
dtype: int64
 
In [48]: d
Out[48]:
    城市     同比     环比     定基
c5  沈阳  101.4  100.1  101.6
c4  深圳  140.9  102.0  145.5
c3  广州  119.4  101.3  120.0
c2  上海  127.3  101.2  127.8
c1  北京  120.7  101.5  121.4
 
In [49]: d.drop('c5')
Out[49]:
    城市     同比     环比     定基
c4  深圳  140.9  102.0  145.5
c3  广州  119.4  101.3  120.0
c2  上海  127.3  101.2  127.8
c1  北京  120.7  101.5  121.4
 
In [50]: d.drop('同比',axis=1)
Out[50]:
    城市     环比     定基
c5  沈阳  100.1  101.6
c4  深圳  102.0  145.5
c3  广州  101.3  120.0
c2  上海  101.2  127.8
c1  北京  101.5  121.4
四、Pandas库的数据类型运算
算术运算法则

算术运算根据行列索引,补齐后运算,运算默认产生浮点数

补齐时缺项填充NaN (空值 ) 二维和一维、一维和零维间为广播运算

采用 + ‐ * / 符号进行的二元运算产生新的对象

In [51]: import numpy as np
 
In [52]: a=pd.DataFrame(np.arange(12).reshape(3,4))
 
In [53]: a
Out[53]:
   0  1   2   3
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
 
In [54]: b=pd.DataFrame(np.arange(20).reshape(4,5))
 
In [55]: b
Out[55]:
    0   1   2   3   4
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19
 
In [56]: a+b
Out[56]:
      0     1     2     3   4
0   0.0   2.0   4.0   6.0 NaN
1   9.0  11.0  13.0  15.0 NaN
2  18.0  20.0  22.0  24.0 NaN
3   NaN   NaN   NaN   NaN NaN
 
In [57]: a*b
Out[57]:
      0     1      2      3   4
0   0.0   1.0    4.0    9.0 NaN
1  20.0  30.0   42.0   56.0 NaN
2  80.0  99.0  120.0  143.0 NaN
3   NaN   NaN    NaN    NaN NaN
数据类型的算术运算

方法形式的运算

方法说明
.add(d,**argws)类型间加法运算,可选参数
.sub(d,**argws)类型间减法运算,可选参数
.mul(d,**argws) 类型间乘法运算,可选参数
.div(d,**argws)类型间除法运算,可选参数
In [58]: b.add(a,fill_value=100)
Out[58]:
       0      1      2      3      4
0    0.0    2.0    4.0    6.0  104.0
1    9.0   11.0   13.0   15.0  109.0
2   18.0   20.0   22.0   24.0  114.0
3  115.0  116.0  117.0  118.0  119.0
 
In [59]: a.mul(b,fill_value=0)
Out[59]:
      0     1      2      3    4
0   0.0   1.0    4.0    9.0  0.0
1  20.0  30.0   42.0   56.0  0.0
2  80.0  99.0  120.0  143.0  0.0
3   0.0   0.0    0.0    0.0  0.0
 
In [61]: c=pd.Series(np.arange(4))
 
In [62]: c
Out[62]:
0    0
1    1
2    2
3    3
dtype: int32
 
In [63]: c-10
Out[63]:
0   -10
1    -9
2    -8
3    -7
dtype: int32
 
In [64]: b-c
Out[64]:
      0     1     2     3   4
0   0.0   0.0   0.0   0.0 NaN
1   5.0   5.0   5.0   5.0 NaN
2  10.0  10.0  10.0  10.0 NaN
3  15.0  15.0  15.0  15.0 NaN
 
In [65]: b.sub(c,axis=0)
Out[65]:
    0   1   2   3   4
0   0   1   2   3   4
1   4   5   6   7   8
2   8   9  10  11  12
3  12  13  14  15  16

注意:

  1. fill_value参数替代NaN,替代后参与运算

  2. 不同维度间为广播运算,一维Series默认在轴 1参与运算

  3. 使用运算方法可以令一维Series参与轴 0运算

比较运算法则

比较运算只能比较相同索引的元素,不进行补齐

二维和一维、一维和零维间为广播运算

采用 > < >= <= == != 等符号进行的二元运算产生布尔对象

In [66]: d=pd.DataFrame(np.arange(12,0,-1).reshape(3,4))
 
In [68]: a<d
Out[68]:
       0      1      2      3
0   True   True   True   True
1   True   True  False  False
2  False  False  False  False
 
In [69]: a>d
Out[69]:
       0      1      2      3
0  False  False  False  False
1  False  False  False   True
2   True   True   True   True
 
In [70]: a==d
Out[70]:
       0      1      2      3
0  False  False  False  False
1  False  False   True  False
2  False  False  False  False
 
In [71]: a>c
Out[71]:
       0      1      2      3
0  False  False  False  False
1   True   True   True   True
2   True   True   True   True
 
In [72]: c>0
Out[72]:
0    False
1     True
2     True
3     True
dtype: bool

注意:

  1. 同维度运算,尺寸一致

  2. 不同维度,广播运算,默认在 1 轴

五、Pandas数据特征分析
1. Pandas库的数据排序

.sort_index()方法在指定轴上根据索引进行排序,默认升序

.sort_index(axis=0, ascending=True)

In [1]: import pandas as pd
 
In [2]: import numpy as np
 
In [3]: b=pd.DataFrame(np.arange(20).reshape(4,5),index=['c','a','d','b'])
 
In [4]: b
Out[4]:
    0   1   2   3   4
c   0   1   2   3   4
a   5   6   7   8   9
d  10  11  12  13  14
b  15  16  17  18  19
 
In [5]: b.sort_index()
Out[5]:
    0   1   2   3   4
a   5   6   7   8   9
b  15  16  17  18  19
c   0   1   2   3   4
d  10  11  12  13  14
 
In [6]: b.sort_index(ascending=False)
Out[6]:
    0   1   2   3   4
d  10  11  12  13  14
c   0   1   2   3   4
b  15  16  17  18  19
a   5   6   7   8   9
 
In [7]: c=b.sort_index(axis=1,ascending=False)
 
In [8]: c
Out[8]:
    4   3   2   1   0
c   4   3   2   1   0
a   9   8   7   6   5
d  14  13  12  11  10
b  19  18  17  16  15
 
In [9]: c=c.sort_index()
 
In [10]: c
Out[10]:
    4   3   2   1   0
a   9   8   7   6   5
b  19  18  17  16  15
c   4   3   2   1   0
d  14  13  12  11  10

.sort_values()方法在指定轴上根据数值进行排序,默认升序

Series.sort_values(axis=0, ascending=True)

DataFrame.sort_values(by, axis=0, ascending=True)

by : axis轴上的某个索引或索引列表

实例:(NaN统一放到排序末尾)

In [15]: a=pd.DataFrame(np.arange(12).reshape(3,4),index=['a','b','c']
    ...: )
 
In [16]: a
Out[16]:
   0  1   2   3
a  0  1   2   3
b  4  5   6   7
c  8  9  10  11
 
In [17]: c=a+b
 
In [18]: c
Out[18]:
      0     1     2     3   4
a   5.0   7.0   9.0  11.0 NaN
b  19.0  21.0  23.0  25.0 NaN
c   8.0  10.0  12.0  14.0 NaN
d   NaN   NaN   NaN   NaN NaN
 
In [19]: c.sort_values(2,ascending=False)
Out[19]:
      0     1     2     3   4
b  19.0  21.0  23.0  25.0 NaN
c   8.0  10.0  12.0  14.0 NaN
a   5.0   7.0   9.0  11.0 NaN
d   NaN   NaN   NaN   NaN NaN
 
In [20]: c.sort_values(2,ascending=True)
Out[20]:
      0     1     2     3   4
a   5.0   7.0   9.0  11.0 NaN
c   8.0  10.0  12.0  14.0 NaN
b  19.0  21.0  23.0  25.0 NaN
d   NaN   NaN   NaN   NaN NaN
2. 数据的基本统计分析函数

适用于Series和DataFrame类型

方法说明
.sum()计算数据的总和,按0轴计算,下同
.count()非NaN值的数量
.mean() .median()计算数据的算术平均值、算术中位数
.var()`` .std()计算数据的方差、标准差
.min()`` .max()计算数据的最小值、最大值

适用于Series类型

方法说明
.argmin()`` .argmax()计算数据最大值、最小值所在位置的索引位置(自动索引)
.idxmin()`` .idxmax()计算数据最大值、最小值所在位置的索引(自定义索引)
方法说明
.describe()针对0轴(各列)的统计汇总
In [21]: a=pd.Series([9,8,7,6],index=['a','b','c','d'])
 
In [22]: a
Out[22]:
a    9
b    8
c    7
d    6
dtype: int64
 
In [23]: a.describe()
Out[23]:
count    4.000000
mean     7.500000
std      1.290994
min      6.000000
25%      6.750000
50%      7.500000
75%      8.250000
max      9.000000
dtype: float64
 
In [24]: type(a.describe())
Out[24]: pandas.core.series.Series
 
In [25]: a.describe()['count']
Out[25]: 4.0
 
In [26]: a.describe()['max']
Out[26]: 9.0
 
In [27]: b=pd.DataFrame(np.arange(20).reshape(4,5),index=['c','a','d','b'])
 
In [28]: b.describe()
Out[28]:
               0          1          2          3          4
count   4.000000   4.000000   4.000000   4.000000   4.000000
mean    7.500000   8.500000   9.500000  10.500000  11.500000
std     6.454972   6.454972   6.454972   6.454972   6.454972
min     0.000000   1.000000   2.000000   3.000000   4.000000
25%     3.750000   4.750000   5.750000   6.750000   7.750000
50%     7.500000   8.500000   9.500000  10.500000  11.500000
75%    11.250000  12.250000  13.250000  14.250000  15.250000
max    15.000000  16.000000  17.000000  18.000000  19.000000
 
In [29]: type(b.describe())
Out[29]: pandas.core.frame.DataFrame
 
In [30]: b.describe().ix['max']
Out[30]:
0    15.0
1    16.0
2    17.0
3    18.0
4    19.0
Name: max, dtype: float64
 
In [32]: b.describe()[2]
Out[32]:
count     4.000000
mean      9.500000
std       6.454972
min       2.000000
25%       5.750000
50%       9.500000
75%      13.250000
max      17.000000
Name: 2, dtype: float64
3. 数据的累计统计分析

累计统计分析函数(1)

方法说明
.cumsum()依次给出前1、2、…、n个数的和
.cumprod()依次给出前1、2、…、n个数的积
.cummax()依次给出前1、2、…、n个数的最大值
.cummin()依次给出前1、2、…、n个数的最小值
In [33]: b=pd.DataFrame(np.arange(20).reshape(4,5),index=['c','a','d','b'])
 
In [34]: b
Out[34]:
    0   1   2   3   4
c   0   1   2   3   4
a   5   6   7   8   9
d  10  11  12  13  14
b  15  16  17  18  19
 
In [35]: b.cumsum()
Out[35]:
    0   1   2   3   4
c   0   1   2   3   4
a   5   7   9  11  13
d  15  18  21  24  27
b  30  34  38  42  46
 
In [36]: b.cumprod()
Out[36]:
   0     1     2     3     4
c  0     1     2     3     4
a  0     6    14    24    36
d  0    66   168   312   504
b  0  1056  2856  5616  9576
 
In [37]: b.cummin()
Out[37]:
   0  1  2  3  4
c  0  1  2  3  4
a  0  1  2  3  4
d  0  1  2  3  4
b  0  1  2  3  4
 
In [38]: b.cummax()
Out[38]:
    0   1   2   3   4
c   0   1   2   3   4
a   5   6   7   8   9
d  10  11  12  13  14
b  15  16  17  18  19
4. 数据的相关分析

相关分析定义:两个事物,表示为X和Y,如何判断它们之间的存在相关性?

相关性

  • X增大,Y增大,两个变量正相关

  • X增大,Y减小,两个变量负相关

  • X增大,Y无视,两个变量不相关

相关性的度量

① 协方差:两个事物,表示为X和Y,如何判断它们之间的存在相关性?
c o v ( X , Y ) = ∑ i = 1 n ( X i − X ˉ ) ( Y i − Y ˉ ) n − 1 cov(X,Y)= \frac{\sum_{i=1}^{n}(X_i-\bar{X})(Y_i-\bar{Y})}{n-1} cov(X,Y)=n1i=1n(XiXˉ)(YiYˉ)

  • 协方差>0, X和Y正相关

  • 协方差<0, X和Y负相关

  • 协方差=0, X和Y独立无关

② Pearson相关系数:两个事物,表示为X和Y,如何判断它们之间的存在相关性?(r取值范围[‐1,1])

r = ∑ i = 1 n ( x i − x ˉ ) ( y i − y ˉ ) ∑ i = 1 n ( x i − x ˉ ) 2 ∑ i = 1 n ( y i − y ˉ ) 2 r= \frac{\sum_{i=1}^{n}(x_i-\bar{x})(y_i-\bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i-\bar{x})^2}\sqrt{\sum_{i=1}^{n}(y_i-\bar{y})^2}} r=i=1n(xixˉ)2 i=1n(yiyˉ)2 i=1n(xixˉ)(yiyˉ)

  • 0.8‐1.0 极强相关

  • 0.6‐0.8 强相关

  • 0.4‐0.6 中等程度相关

  • 0.2‐0.4 弱相关

  • 0.0‐0.2 极弱相关或无相关

相关分析函数

适用于Series和DataFrame类型

方法说明
.cov()计算协方差矩阵
.corr()计算相关系数矩阵, Pearson、Spearman、Kendall等系数

实例:房价增幅与M2增幅的相关性

In [42]: hprice=pd.Series([3.04,22.93,12.75,22.6,12.33],index=['2008','2009','2010','2011','2012'])
 
In [43]: m2=pd.Series([8.18,18.38,9.13,7.82,6.69],index=['2008','2009','2010','2011','2012'])
 
In [44]: hprice.corr(m2)
Out[44]: 0.5239439145220387
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值