您的位置:首页 > 其它

pandas小记:pandas计算工具-汇总统计

2017-08-14 00:00 585 查看
http://
blog.csdn.net/pipisorry/article/details/25625799

汇总和计算描述统计:统计函数

pandas对象拥有一组常用的数学和统计方法。它们大部分都属于约简和汇总统计,用于从Series中提取的个值(如sum或mean)或从DataFrame的行或列中提取一个Series。

跟对应的NumPy数组方法相比,它们都是基于没有缺失数据的假设而构建的。

数学运算和约简(比如对某个轴求和)可以根据不同的元数据(轴编号)执行。灵活处理缺失数据。

描述和汇总统计

方法 说明
count 非NA值的数量
describe 针对Series或各DataFrame列计算汇总统计
min,max 计算最小值和最大值
argmin,argmax 计算能够获取到最小值和最大值的索引位置(整数)
idxmin,idxmax 计算能够获取到最小值和最大值的索引值
quantile 计算样本的分位数(0到 1)
sum 值的总和
mean 值的平均数, a.mean() 默认对每一列的数据求平均值;若加上参数a.mean(1)则对每一行求平均值
media 值的算术中位数(50%分位数)
mad 根据平均值计算平均绝对离差
var 样本值的方差
std 样本值的标准差
skew 样本值的偏度(三阶矩)
kurt 样本值的峰度(四阶矩)
cumsum 样本值的累计和
cummin,cummax 样本值的累计最大值和累计最小
cumprod 样本值的累计积
diff 计算一阶差分(对时间序列很有用)
pct_change 计算百分数变化

>>>df = DataFrame([[1.4, np.nan], [7.1, -4.5], [np.nan, np.nan], [0.75,-1.3]],index=['a','b','c','d'],columns=[ 'one', 'two'])
>>>df

one two
a 1.40 NaN
b 7.10 -4.5
c NaN NaN
d 0.75 -1.3

约简方法

这些方法并不会改变dataframe本身,而是返回一个改变的值?

约简方法的选项

选项 说明
axis 约简的轴。DataFrame的行用0,列用1
skipna 排除缺失值,默认值为True
level 如果轴是层次化索引的(即Multiindex),则根据level分组约简

df.sum()

>>> df.sum() #返回一个含有列小计的Series
one 9.25
two -5.80
dtype: float64
#传入axis=1将会按行进行求和运算:
>>> df.sum(axis=1)
a 1.40
b 2.60
c NaN
d -0.55
dtype: float64
NA值会自动被排除,除非整个切片(这里指的是行或列)都是NA。

通过skipna选项可 以禁用该功能:
>>> df.mean(axis=1, skipna=False)
a NaN
b 1.300
c NaN
d -0.275
dtype: float64

df.mean()

计算df行均值df.mean(axis = 1)

相当于将其转换成numpy.array后进行下面操作

user_rat_cnt = [np.count_nonzero(rat_array[i]) for i in range(len(rat_array))]  # 每个用户打分个数 user_rat_mean = rat_array.sum(axis=1) / user_rat_cnt  # 每个用户打分均值 print(user_rat_mean)


df.sub

Operating with objects that have different dimensionality and need alignment.In addition, pandas automatically broadcasts along the specified dimension.

Equivalent to dataframe - other, but with support to substitute a fill_value for missing data in one of the inputs.

In [63]: s = pd.Series([1,3,5,np.nan,6,8], index=dates).shift(2)
In [64]: s
Out[64]:
2013-01-01 NaN
2013-01-02 NaN
2013-01-03 1
2013-01-04 3
2013-01-05 5
2013-01-06 NaN
Freq: D, dtype: float64

In [65]: df.sub(s, axis='index')
Out[65]:
A B C D F
2013-01-01 NaN NaN NaN NaN NaN
2013-01-02 NaN NaN NaN NaN NaN
2013-01-03 -1.861849 -3.104569 -1.494929 4 1
2013-01-04 -2.278445 -3.706771 -4.039575 2 0
2013-01-05 -5.424972 -4.432980 -4.723768 0 -1
2013-01-06 NaN NaN NaN NaN NaN


df.sub参数axis:

pandas.dataframe每行都减去行平均值

use DataFrame's sub method and specify that the subtraction should happen row-wise (axis=0) as opposed to the default column-wise behaviour:

df.sub(df.mean(axis=1), axis=0)


df.std

注意标准差或者方差的计算

DataFrame.
std (
axis=None,
skipna=None,
level=None,
ddof=1,
numeric_only=None,
**kwargs )

Return unbiased standard deviation over requested axis.

Normalized by N-1 by default. This can be changed using the ddof argument

Parameters:axis : {index (0), columns (1)}
skipna : boolean, default True

Exclude NA/null values. If an entire row/column is NA, the resultwill be NA

这里ddof默认值=1,是无偏估计,计算的是样本标准差,分母是n-1不是n。
参数设置为ddof=0才是有偏估计,计算的是总体标准差。

idxmin和idxmax

返回的是间接统计(比如达到最小值或最大值的索引):
>>> df.idxmax()
one b
two d

累计型计算cumsum

>>> df.cumsum()

多个汇总统计describe

既不是约简型也不是累计型。用于一次性 产生多个汇总统计:
>>> df.describe()

one two
count 3.000000 2.000000
mean 3.083333 -2.900000
std 3.493685 2.262742
min 0.750000 -4.500000
25% 1.075000 -3.700000
50% 1.400000 -2.900000
75% 4.250000 -2.100000
max 7.100000 -1.300000

对于非数值型数据,describe会产生另外一种汇总统计:
>>>obj = Series(['a','a','b','c'] * 4)
>>>obj
>>>obj.describe()
count 16
unique 3
top a
freq 8
dtype: object

[Binary operator functions]

[Basic section on Binary Ops]

皮皮Blog

相关系数与协方差

有些汇总统计(如相关系数和协方差)是通过参数对计算出来的。

DataFrame数据

下面几个 DataFrame数据来自Yahoo! Finance的股票价格和成交量:
>>>import pandas.io.data as web
>>> all_data = {}
for ticker in ['AAPL','IBM','MSFT','GOOG']:
all_data[ticker] = web.get_data_yahoo(ticker,'1/1/2000','1/1/2010')
>>>price = pd.DataFrame({tic: data['Adj Close'] for tic, data in all_data.items()})

In[15]: price.head()
Out[15]:
AAPL GOOG IBM MSFT
Date
2000-01-03 3.702290 NaN 90.897237 40.369145
2000-01-04 3.390148 NaN 87.811825 39.005468
2000-01-05 3.439760 NaN 90.897237 39.416736
2000-01-06 3.142089 NaN 89.330044 38.096351
2000-01-07 3.290924 NaN 88.938245 38.594201

>>>volume = pd.DataFrame({tic: data['Volume'] for tic, data in all_data.items()})

In[18]: volume.head()
Out[18]:
AAPL GOOG IBM MSFT
Date
2000-01-03 133949200 NaN 10347700 53228400
2000-01-04 128094400 NaN 8227800 54119000
2000-01-05 194580400 NaN 12733200 64059600
2000-01-06 191993200 NaN 7971900 54976600
2000-01-07 115183600 NaN 11856700 62013600

计算价格的百分数变化

>>>returns = price.pct_change()
In[20]: returns.tail()
Out[20]:
AAPL GOOG IBM MSFT
Date
2009-12-24 0.034339 0.011117 0.004385 0.002587
2009-12-28 0.012294 0.007098 0.013326 0.005484
2009-12-29 -0.011861 -0.005571 -0.003477 0.007058
2009-12-30 0.012147 0.005376 0.005461 -0.013699
2009-12-31 -0.004300 -0.004416 -0.012597 -0.015504

Series.corr方法和cov

用于计算两个Series中重叠的、非NA的、按索引对齐的值的相关系数。与此类似,cov用干计算协方差:
>>>returns.MSFT.corr(returns.IBM)
0.49597970053200319
>>>returns.MSFT.cov(returns.IBM)
0.00021595764765417841
DataFrame的corr和cov方法将以DataFrame的形式返回完整的相关系数或协方差矩阵:
>>>returns.corr()

AAPL GOOG IBM MSFT
AAPL 1.000000 0.470676 0.410011 0.424305
GOOG 0.470676 1.000000 0.390689 0.443587
IBM 0.410011 0.390689 1.000000 0.495980
MSFT 0.424305 0.443587 0.495980 1.000000

Note:相关系数方法
DataFrame.corr(method='pearson', min_periods=1)

Compute pairwise correlation of columns, excluding NA/null values

Parameters:

method : {‘pearson’, ‘kendall’, ‘spearman’}

pearson : standard correlation coefficient

kendall : Kendall Tau correlation coefficient

spearman : Spearman rank correlation

min_periods : int, optional

Minimum number of observations required per pair of columns to have a valid result. Currently only available for pearson and spearman correlation

Returns:

y : DataFrame

DataFrame.corrwith方法

利用DataFrame的corrwith方法,可以计算其列或行跟另一个Series或DataFrame之间的相关系数。传入一个Series将会返回一个相关系数值Series (针对各列进行计算):
>>> returns.corrwith(returns.IBM)
AAPL 0.410011
GOOG 0.390689
IBM 1.000000
MSFT 0.495980
传入一个DataFrame则会计算按列名配对的相关系数。下面计算了百分比变化与成交量的相关系数:
>>> returns.corrwith(volume)
AAPL -0.057549
GOOG 0.062647
IBM -0.007892
MSFT -0.014245
dtype: float64
传入axis=1即可按行进行计算。

无论如何,在计算相关系数之前,所有的数据项都会按标签对齐。

[Statistical Functions]

皮皮Blog

窗口函数

[Window Functions]

皮皮Blog

聚合Aggregation

[
Aggregation]

from:
http://blog.csdn.net/pipisorry/article/details/25625799

ref: [Computational tools
]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: