pandas小记:pandas计算工具-汇总统计
2017-09-22 14:28
501 查看
http://blog.csdn.net/pipisorry/article/details/25625799
跟对应的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
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
相当于将其转换成numpy.array后进行下面操作
Equivalent to dataframe - other, but with support to substitute a fill_value for missing data in one of the inputs.
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:
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
这里ddof默认值=1,是无偏估计,计算的是样本标准差,分母是n-1不是n。
参数设置为ddof=0才是有偏估计,计算的是总体标准差。
>>> df.idxmax()
one b
two d
>>> 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
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
>>> 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
皮皮Blog
聚合Aggregation
[Aggregation]
from: http://blog.csdn.net/pipisorry/article/details/25625799
ref: [Computational tools¶]
汇总和计算描述统计:统计函数
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() #返回一个含有列小计的Seriesone 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=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¶]
pandas 根据多列的数据的值的情况判断来生成另外一列的数值?
def do_something(x, y): return x * y df['new_col'] = map(lambda x, y: do_something(x, y) , df['col_1'], df['col_2'])
4.获取dataFrame的行数和列数,使用的命令是:dataframe.shape[0]和dataframe.shape[1]
此外,获取行数还有方法:len(DataFrame.index)
相关文章推荐
- pandas小记:pandas计算工具-汇总统计
- 利用Python进行数据分析(9) pandas基础: 汇总统计和计算
- pandas汇总和计算描述统计
- pandas带有重复值的轴索引,汇总和计算描述统计,相关系数与协方差
- pandas的汇总和计算描述统计
- Pyhton科学计算工具Pandas(五)—— 常用的数值计算和统计方法
- 利用 Python 进行数据分析(九)pandas 汇总统计和计算
- python:pandas(3),汇总和计算描述统计
- python数据分析之Pandas:汇总和计算描述统计
- pandas之汇总和计算描述统计到层次化索引
- python数据分析pandas包入门学习(三)汇总和统计描述
- R---用于统计计算和统计制图的优秀工具,S 语言的一种实现
- 一共81个,开源大数据处理工具汇总:查询引擎、流式计算、迭代计算、离线计算、键值存储、表格存储、文件存储、资源管理、日志收集系统、消息系统、分布式服务、集群管理、基础设施、搜索引擎、数据挖掘=监控
- 一共81个,开源大数据处理工具汇总:查询引擎、流式计算、迭代计算、离线计算、键值存储、表格存储、文件存储、资源管理、日志收集系统、消息系统、分布式服务、集群管理、基础设施、搜索引擎、数据挖掘=监控
- Pyhton科学计算工具Pandas(九)—— 数据分组
- 汇总统计数据工具—你所不知道的arcgis工具
- Pyhton科学计算工具Pandas(十)—— 透视表和交叉表
- 代码分析/统计工具汇总
- 数据分析之Pandas(三):汇总、统计、相关系数和协方差
- pandas 计算工具