目录

统计功能(Statistical Functions)

统计方法有助于理解和分析数据的行为。 我们现在将学习一些统计函数,我们可以在Pandas对象上应用它们。

Percent_change

Series,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()

output如下 -

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()对列进行操作; 如果要明智地应用相同的行,则使用axis=1()参数。

协方差(Covariance)

协方差应用于系列数据。 Series对象有一个方法cov来计算系列对象之间的协方差。 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)

output如下 -

-0.12978405324

协方差方法应用于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()

output如下 -

-0.58312921152741437
           a           b           c           d            e
a   1.780628   -0.583129   -0.185575    0.003679    -0.136558
b  -0.583129    1.297011    0.136530   -0.523719     0.251064
c  -0.185575    0.136530    0.915227   -0.053881    -0.058926
d   0.003679   -0.523719   -0.053881    1.521426    -0.487694
e  -0.136558    0.251064   -0.058926   -0.487694     0.960761

Note - 观察第一个语句中ab列之间的cov ,同样是DataFrame上cov返回的值。

相关性(Correlation)

相关性显示任意两个值数组(系列)之间的线性关系。 有多种方法可以计算相关性,如pearson(默认值),spearman和kendall。

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()

output如下 -

-0.383712785514
           a          b          c          d           e
a   1.000000  -0.383713  -0.145368   0.002235   -0.104405
b  -0.383713   1.000000   0.125311  -0.372821    0.224908
c  -0.145368   0.125311   1.000000  -0.045661   -0.062840
d   0.002235  -0.372821  -0.045661   1.000000   -0.403380
e  -0.104405   0.224908  -0.062840  -0.403380    1.000000

如果DataFrame中存在任何非数字列,则会自动将其排除。

数据排名

数据排名为元素数组中的每个元素生成排名。 如果是关系,则指定平均等级。

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()

output如下 -

a  1.0
b  3.5
c  2.0
d  3.5
e  5.0
dtype: float64

Rank可选择采用升序参数,默认为true; 当为假时,数据反向排序,较大的值分配较小的等级。

Rank支持使用方法参数指定的不同打破平局方法 -

  • average - 平均排名组

  • min - 小组中的最低排名

  • max - 该组中的最高排名

  • first - 按照它们在数组中出现的顺序分配的排名

↑回到顶部↑
WIKI教程 @2018