1. 程式人生 > 程式設計 >pandas的相關係數與協方差例項

pandas的相關係數與協方差例項

1、輸出百分比變化以及前後指定的行數

  a = np.arange(1,13).reshape(6,2)
  data = DataFrame(a)
  #計算列的百分比變化,如果想計算行設定axis=1
  print(data.pct_change())
  '''
       0     1
   0    NaN    NaN
   1 2.000000 1.000000
   2 0.666667 0.500000
   3 0.400000 0.333333
   4 0.285714 0.250000
   5 0.222222 0.200000
  '''
  #輸出前五行,預設是5,可以通過設定n引數來設定輸出的行數
  print(data.head())
  '''
    0  1
  0 1  2
  1 3  4
  2 5  6
  3 7  8
  4 9 10
  '''
  #輸出最後五行
  print(data.tail())
  '''
    0  1
  1  3  4
  2  5  6
  3  7  8
  4  9 10
  5 11 12
  '''

2、計算DataFrame列與列的相關係數和協方差

 a = np.arange(1,10).reshape(3,3)
  data = DataFrame(a,index=["a","b","c"],columns=["one","two","three"])
  print(data)
  '''
    one two three
  a  1  2   3
  b  4  5   6
  c  7  8   9
  '''
  #計算第一列和第二列的相關係數
  print(data.one.corr(data.two))
  #1.0
  #返回一個相關係數矩陣
  print(data.corr())
  '''
      one two three
  one  1.0 1.0  1.0
  two  1.0 1.0  1.0
  three 1.0 1.0  1.0
  '''
  #計算第一列和第二列的協方差
  print(data.one.cov(data.two))
  #9.0
  #返回一個協方差矩陣
  print(data.cov())
  '''
      one two three
  one  9.0 9.0  9.0
  two  9.0 9.0  9.0
  three 9.0 9.0  9.0
  '''

3、計算DataFrame與列或者Series的相關係數

  a = np.arange(1,"three"])
  print(data)
  '''
    one two three
  a  1  2   3
  b  4  5   6
  c  7  8   9
  '''
  #計算data與第三列的相關係數
  print(data.corrwith(data.three))
  '''
  one   1.0
  two   1.0
  three  1.0
  '''
  #計算data與Series的相關係數
  #在定義Series的時候,索引一定要去DataFrame的索引一樣
  s = Series([5,3,1],"c"])
  print(data.corrwith(s))
  '''
  one   -1.0
  two   -1.0
  three  -1.0
  '''

注意:在使用DataFrame或Series在計算相關係數或者協方差的時候,都會計算索引重疊的、非NA的、按照索引對齊原則,對於無法對齊的索引會使用NA值進行填充。在使用DataFrame與指定的行或列或Series計算協方差和相關係數的時候,預設都是與DataFrame的列進行計算,如果想要計算行,設定axis引數為1即可。

以上這篇pandas的相關係數與協方差例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。