pandas的相关系数与协方差实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

pandas的相关系数与协方差实例

  2021-04-02 我要评论

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,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
  '''
  #计算data与第三列的相关系数
  print(data.corrwith(data.three))
  '''
  one   1.0
  two   1.0
  three  1.0
  '''
  #计算data与Series的相关系数
  #在定义Series的时候,索引一定要去DataFrame的索引一样
  s = Series([5,3,1],index=["a","b","c"])
  print(data.corrwith(s))
  '''
  one   -1.0
  two   -1.0
  three  -1.0
  '''

注意:在使用DataFrame或Series在计算相关系数或者协方差的时候,都会计算索引重叠的、非NA的、按照索引对齐原则,对于无法对齐的索引会使用NA值进行填充。在使用DataFrame与指定的行或列或Series计算协方差和相关系数的时候,默认都是与DataFrame的列进行计算,如果想要计算行,设置axis参数为1即可。

以上这篇pandas的相关系数与协方差实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们