这一小节介绍pandas的统计函数;
1.排序
import pandas as pd
import numpy as np
np.random.seed(1)#保证每次的随机种子一样,跑出来的数据一样;
s1 = pd.Series(np.random.normal(size = 5))
#对子序列计算平方数
print(pow(s1,2)) #直接计算平方数
#根绝索引或序列值排序
print(s1.sort_index(ascending = False)) #根据索引降序排序;
print(s1.sort_values(ascending = False)) #根据序列的值降序排序;
0 2.638498
1 0.374246
2 0.278965
3 1.151262
4 0.748930
dtype: float64
4 0.865408
3 -1.072969
2 -0.528172
1 -0.611756
0 1.624345
dtype: float64
0 1.624345
4 0.865408
2 -0.528172
1 -0.611756
3 -1.072969
dtype: float64
2.采样:
s.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
n:指定抽取的样本量;
frac:指定抽取的样本比例;
replace:是否有放回抽样,默认无放回;
weights:指定样本抽中的概率,默认等概论抽样;
random_state:指定抽样的随机种子,可以使得每次抽样的种子一样,每次抽样结果一样;
s = pd.Series(range(1,101)) s1 = pd.Series(['男','女']) print(s.sample(n=3,random_state = 1)) print(s1.sample(n=10,replace = True, weights= [0.2,0.8],random_state = 2))
20 21 10 11 96 97 dtype: int32 1 女 0 男 1 女 1 女 1 女 1 女 1 女 1 女 1 女 1 女 dtype: object
3.describe函数:包括对序列的计数,求和,均值,最大值,最小值等等;
s = pd.Series(range(1,101)) print(s.describe())
count 100.000000 mean 50.500000 std 29.011492 min 1.000000 25% 25.750000 50% 50.500000 75% 75.250000 max 100.000000 dtype: float64
其他统计函数:
s.min() # 最小值
s.quantile(q=[0,0.25,0.5,0.75,1]) # 分位数函数
s.median() # 中位数
s.mode() # 众数
s.mean() # 平均值
s.mad() # 平均绝对误差
s.max # 最大值
s.sum() # 和
s.std() # 标准差
s.var() # 方差
s.skew() # 偏度
s.kurtosis() # 峰度
s.cumsum() # 和的累计,返回序列
s.cumprod() # 乘积的累积,返回序列
s.product() # 序列元素乘积
s.diff() # 序列差异(微分),返回序列
s.abs() # 绝对值,返回序列
s.pct_change() # 百分比变化 ,返回序列
s.corr(s2) # 相关系数
s.ptp() # 极差 R中的range函数