python协方差相等_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,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的相关系数与协方差实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值