pandas的相關系數與協方差實例
更新時間:2019年12月27日 09:50:02 作者:修煉之路
今天小編就為大家分享一篇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的相關系數與協方差實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
使用Python將PDF表格提取到文本,CSV和Excel文件中
本文將介紹如何使用簡單的Python代碼從PDF文檔中提取表格數據并將其寫入文本、CSV和Excel文件,從而輕松實現PDF表格的自動化提取,有需要的可以參考下2024-11-11

