[數據分析基礎] 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,如何判斷它們之間的存在相關性?
cov(X,Y)=i=1n(XiXˉ)(YiYˉ)n1cov(X,Y)= \frac{\sum_{i=1}^{n}(X_i-\bar{X})(Y_i-\bar{Y})}{n-1}

  • 協方差>0, X和Y正相關

  • 協方差<0, X和Y負相關

  • 協方差=0, X和Y獨立無關

② Pearson相關係數:兩個事物,表示爲X和Y,如何判斷它們之間的存在相關性?(r取值範圍[‐1,1])

r=i=1n(xixˉ)(yiyˉ)i=1n(xixˉ)2i=1n(yiyˉ)2r= \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}}

  • 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章