One - One Code All

Blog Content

pandas的相关系数与协方差

Python 统计学-科学计算   2013-05-09 23:15:44
    
    # 输出百分比变化以及前后指定的行数
    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
    '''

    # 计算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
    '''

    # 计算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即可。
    '''



上一篇:sklearn数据预处理之归一化,标准化,正则化
下一篇:pandas常用统计方法

The minute you think of giving up, think of the reason why you held on so long.