統(tǒng)計方法有助于理解和分析數(shù)據(jù)的行為?,F(xiàn)在我們將學(xué)習(xí)一些統(tǒng)計函數(shù),可以將這些函數(shù)應(yīng)用到Pandas的對象上。
系列,DatFrames和Panel都有pct_change()函數(shù)。此函數(shù)將每個元素與其前一個元素進行比較,并計算變化百分比。
import pandas as pd
import numpy as np
s = pd.Series([1,2,3,4,5,4])
print (s.pct_change())
df = pd.DataFrame(np.random.randn(5, 2))
print (df.pct_change())
執(zhí)行上面示例代碼,得到以下結(jié)果 -
0 NaN
1 1.000000
2 0.500000
3 0.333333
4 0.250000
5 -0.200000
dtype: float64
0 1
0 NaN NaN
1 -15.151902 0.174730
2 -0.746374 -1.449088
3 -3.582229 -3.165836
4 15.601150 -1.860434
默認情況下,pct_change()對列進行操作; 如果想應(yīng)用到行上,那么可使用axis = 1參數(shù)。
協(xié)方差適用于系列數(shù)據(jù)。Series對象有一個方法cov用來計算序列對象之間的協(xié)方差。NA將被自動排除。
Cov系列示例
import pandas as pd
import numpy as np
s1 = pd.Series(np.random.randn(10))
s2 = pd.Series(np.random.randn(10))
print (s1.cov(s2))
執(zhí)行上面示例代碼,得到以下結(jié)果 -
0.0667296739178
當應(yīng)用于DataFrame時,協(xié)方差方法計算所有列之間的協(xié)方差(cov)值。
import pandas as pd
import numpy as np
frame = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
print (frame['a'].cov(frame['b']))
print (frame.cov())
執(zhí)行上面示例代碼,得到以下結(jié)果 -
-0.406796939839
a b c d e
a 0.784886 -0.406797 0.181312 0.513549 -0.597385
b -0.406797 0.987106 -0.662898 -0.492781 0.388693
c 0.181312 -0.662898 1.450012 0.484724 -0.476961
d 0.513549 -0.492781 0.484724 1.571194 -0.365274
e -0.597385 0.388693 -0.476961 -0.365274 0.785044
注 - 觀察第一個語句中
a和b列之間的cov結(jié)果值,與由DataFrame上的cov返回的值相同。
相關(guān)性顯示了任何兩個數(shù)值(系列)之間的線性關(guān)系。有多種方法來計算pearson(默認),spearman和kendall之間的相關(guān)性。
import pandas as pd
import numpy as np
frame = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
print (frame['a'].corr(frame['b']))
print (frame.corr())
執(zhí)行上面示例代碼,得到以下結(jié)果 -
-0.613999376618
a b c d e
a 1.000000 -0.613999 -0.040741 -0.227761 -0.192171
b -0.613999 1.000000 0.012303 0.273584 0.591826
c -0.040741 0.012303 1.000000 -0.391736 -0.470765
d -0.227761 0.273584 -0.391736 1.000000 0.364946
e -0.192171 0.591826 -0.470765 0.364946 1.000000
如果DataFrame中存在任何非數(shù)字列,則會自動排除。
數(shù)據(jù)排名為元素數(shù)組中的每個元素生成排名。在關(guān)系的情況下,分配平均等級。
import pandas as pd
import numpy as np
s = pd.Series(np.random.np.random.randn(5), index=list('abcde'))
s['d'] = s['b'] # so there's a tie
print (s.rank())
執(zhí)行上面示例代碼,得到以下結(jié)果 -
a 4.0
b 1.5
c 3.0
d 1.5
e 5.0
dtype: float64
Rank可選地使用一個默認為true的升序參數(shù); 當錯誤時,數(shù)據(jù)被反向排序,也就是較大的值被分配較小的排序。
Rank支持不同的tie-breaking方法,用方法參數(shù)指定 -
average - 并列組平均排序等級min - 組中最低的排序等級max - 組中最高的排序等級first - 按照它們出現(xiàn)在數(shù)組中的順序分配隊列