统计方法有助于理解和分析数据的行为。现在我们将学习一些统计函数,可以将这些函数应用到Pandas的对象上。
系列,DatFrames和Panel都有pct_change()函数。此函数将每个元素与其前一个元素进行比较,并计算变化百分比。
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())
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 1.288538 -0.774621 2 -1.106562 1.607283 3 0.266542 -3.559262 4 1.502060 -1.765976
默认情况下, pct_change()
对列进行操作; 如果想应用到行上,那么可使用 axis = 1
参数。
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))
0.5093096226029427
当应用于DataFrame时,协方差方法计算所有列之间的协方差(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())
-0.025855543630631767 a b c d e a 0.686023 -0.025856 -0.266709 -0.041785 0.062435 b -0.025856 0.270761 0.297274 -0.131492 -0.255465 c -0.266709 0.297274 0.611532 0.118074 -0.130121 d -0.041785 -0.131492 0.118074 0.609805 0.169450 e 0.062435 -0.255465 -0.130121 0.169450 0.869206
注 - 观察第一个语句中a和b列之间的cov结果值,与由DataFrame上的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'].corr(frame['b']))
print (frame.corr())
-0.10242111549641644 a b c d e a 1.000000 -0.102421 -0.049574 -0.408006 0.388186 b -0.102421 1.000000 -0.069152 -0.339662 -0.364997 c -0.049574 -0.069152 1.000000 0.191719 0.373471 d -0.408006 -0.339662 0.191719 1.000000 0.065197 e 0.388186 -0.364997 0.373471 0.065197 1.000000
如果DataFrame中存在任何非数字列,则会自动排除。
import pandas as pd
import numpy as np
s = pd.Series(np.random.randn(5), index=list('abcde'))
s['d'] = s['b'] # so there's a tie
print (s.rank())
a 1.0 b 3.5 c 2.0 d 3.5 e 5.0 dtype: float64
Rank可选地使用一个默认为true的升序参数; 当错误时,数据被反向排序,也就是较大的值被分配较小的排序。
Rank支持不同的 tie-breaking
方法,用方法参数指定
average
- 并列组平均排序等级min
- 组中最低的排序等级max
- 组中最高的排序等级first
- 按照它们出现在数组中的顺序分配队列