pandas的相關系數(shù)與協(xié)方差實例
1、輸出百分比變化以及前后指定的行數(shù)
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參數(shù)來設置輸出的行數(shù)
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列與列的相關系數(shù)和協(xié)方差
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
'''
#計算第一列和第二列的相關系數(shù)
print(data.one.corr(data.two))
#1.0
#返回一個相關系數(shù)矩陣
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
'''
#計算第一列和第二列的協(xié)方差
print(data.one.cov(data.two))
#9.0
#返回一個協(xié)方差矩陣
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的相關系數(shù)
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與第三列的相關系數(shù)
print(data.corrwith(data.three))
'''
one 1.0
two 1.0
three 1.0
'''
#計算data與Series的相關系數(shù)
#在定義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在計算相關系數(shù)或者協(xié)方差的時候,都會計算索引重疊的、非NA的、按照索引對齊原則,對于無法對齊的索引會使用NA值進行填充。在使用DataFrame與指定的行或列或Series計算協(xié)方差和相關系數(shù)的時候,默認都是與DataFrame的列進行計算,如果想要計算行,設置axis參數(shù)為1即可。
以上這篇pandas的相關系數(shù)與協(xié)方差實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
pycharm創(chuàng)建scrapy項目教程及遇到的坑解析
這篇文章主要介紹了pycharm創(chuàng)建scrapy項目教程及遇到的坑解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08
在?Python?中使用變量創(chuàng)建文件名的方法
這篇文章主要介紹了在?Python?中使用變量創(chuàng)建文件名,格式化的字符串文字使我們能夠通過在字符串前面加上 f 來在字符串中包含表達式和變量,本文給大家詳細講解,需要的朋友可以參考下2023-03-03
利用Python腳本在Nginx和uwsgi上部署MoinMoin的教程
這篇文章主要介紹了利用Python腳本在Nginx和uwsgi上部署MoinMoin的教程,示例基于CentOS操作系統(tǒng),需要的朋友可以參考下2015-05-05

