您的位置:首页 > 其它

pandas的相关系数与协方差

2018-01-08 21:36 232 查看
[b]1、输出百分比变化以及前后指定的行数[/b]
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
'''
[b]2、计算DataFrame列与列的相关系数和协方差[/b]

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
'''

[b]3、计算DataFrame与列或者Series的相关系数[/b]
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即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: