【Python】pandas:计算,统计,比较

pandas是Python的扩展库(第三方库),为Python编程语言提供 高性能、易于使用的数据结构和数据分析工具。

pandas官方文档:User Guide — pandas 2.2.2 documentation

帮助:可使用help(...)查看函数说明文档(若是第三方库的函数,需先导入库)。例如:help(pd.DataFrame),help(pd.crosstab)


Python代码中,导入pandas:

import pandas as pd

使用pandas时,通常涉及numpy,若需要也导入numpy:

import numpy as np


1、算术运算

数值行/列可以进行算术运算(加、减、乘、除、取余、幂等)。

2、与其他行/列进行计算

数值行/列可以与其他数值行/列进行计算。

3、用于计算的函数

(3-1)算术运算的函数:add, radd, sub, pow等

有一些函数可以用于算术运算,也可以将两个DataFrame之间进行计算。

例如(加法):DataFrame.add(self, other, axis='columns', level=None, fill_value=None)

注:参数other:数值、序列(如:列表/字典)、Series、另一个DataFrame。

        参数axis:指定轴。若other是Series默认按索引,若other是列表/字典默认按列。

        参数fill_value:指定NaN的填充内容。

常用算术运算的函数
DataFrame.add(...)
DataFrame.sub(...)
DataFrame.mul(...)
DataFrame.div(...)
DataFrame.truediv(...)
DataFrame.floordiv(...)除(返回整数)
DataFrame.mod(...)取余
DataFrame.pow(...)
DataFrame.rsub(...)减(反向)。不是“3-5”而是“5-3”
DataFrame.rdiv(...)除(反向)。不是“3/5”而是“5/3”
DataFrame.rmod(...)取余(反向)。不是“3%5”而是“5%3”
DataFrame.rpow(...)

幂(反向)。不是“3**5”而是“5**3”

DataFrame.abs(...)取绝对值

 

(3-2)累计计算的函数:cumsum, cummax等

有一些函数可以用于指定轴的累计计算(各位置的数值是按指定轴从位置0到该位置累计计算的数值)。

例如(累计求和):DataFrame.cumsum(self, axis=None, skipna=True, *args, **kwargs)

注:参数axis:指定轴。若axis=0 则各列累计计算,若axis=1 则各行累计计算。

       参数skipna:默认skipna=True 跳过NaN。

常用累计计算的函数
DataFrame.cummax(...)指定轴,各位置数值是从位置0到该位置的累计最大值
DataFrame.cummin(...)指定轴,各位置数值是从位置0到该位置的累计最小值
DataFrame.cumsum(...)指定轴,各位置数值是从位置0到该位置的累计求和
DataFrame.cumprod(...)指定轴,各位置数值是从位置0到该位置的累计乘积

 (3-3)计算矩阵乘法的函数:dot

dot(self, other: 'AnyArrayLike | DataFrame') -> 'DataFrame | Series'

  • DataFrame.dot(other):DataFrame与另一个DataFrame或Series进行矩阵乘法。
  • 等效于:DataFrame @ other
  • 注:DataFrame和other维度需兼容(即DataFrame的列数和other的行数相同),才能进行矩阵乘法。结果是新DataFrame(原DataFrame的行数,other的列数)。

 DataFrame.columns和other.index需相同,否则报错:ValueError: matrices are not aligned。

4、用于统计的函数

(4-1)统计数据的函数:sum, max, mean等

有一些函数可以用于统计数据(求和,最大值,最小值,平均值等)。

例如(求和):DataFrame.sum(self, axis=None, skipna=True, level=None, numeric_only=None, min_count=0, **kwargs)

注:参数axis:指定轴。若axis=0 则各列求和,若axis=1 则各行求和。

       参数skipna:默认skipna=True 跳过NaN。

       参数numeric_only:只能浮点数、整型、布尔类型。

       参数min_count:指定非NaN值最小个数,若小于该数值,结果为NaN。

常用统计的函数
DataFrame.sum(...)指定轴,求和
DataFrame.prod(...)指定轴,求乘积
DataFrame.max(...)指定轴,求最大值
DataFrame.idxmax(...)指定轴,求最大值的索引位置
DataFrame.min(...)指定轴,求最小值
DataFrame.idxmin(...)指定轴,求最小值的索引位置
DataFrame.mean(...)指定轴,求平均值
DataFrame.median(...)指定轴,求中位值(排序后位于中间的值,若两个取这两个的平均值)
DataFrame.mode(...)

指定轴,求众数(出现次数最多的数值)

DataFrame.std(...)

指定轴,求标准差(Standard Deviation,σ)

DataFrame.var(...)

指定轴,求方差(Variance,标准差的平方,\sigma ^{2}

DataFrame.cov(...)

指定轴,求协方差(Covariance),方差是协方差的特殊情况(变量相同)

DataFrame.corr(...)

指定轴,求相关系数(Correlation,变量之间线性相关程度,r )

DataFrame.rank(...)

指定轴,求排名

DataFrame.skew(...)指定轴,求倾斜度(偏度)
DataFrame.count(...)

指定轴,统计非NaN值的数量

DataFrame.describe()DataFrame的统计信息
DataFrame.info()

DataFrame的信息

添加一行总计和一列总计。 

统计指定轴 NaN值的数量:DataFrame.isna().sum(axis=指定轴)

统计指定轴 非NaN值的数量:DataFrame.count(axis=指定轴) 或者 DataFrame.notna().sum(axis=指定轴)

统计所有 NaN值的数量:DataFrame.isna().values.sum()

统计所有 非NaN值的数量:DataFrame.notna().values.sum()

共有多少数据:DataFrame.size

(4-2)交叉表(简单统计数量):crosstab

crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins: 'bool' = False, margins_name: 'str' = 'All', dropna: 'bool' = True, normalize=False) -> 'DataFrame'

注:默认dropna=True 整行都是NaN则删除。

  • pd.crosstab(行索引数据, 行索引数据):行索引和列索引都可以是数组或Series或列表形式的数组/Series。获取行索引数据和行索引数据的交叉表(简单统计数量) 。
  • pd.crosstab(行索引数据, 行索引数据, margins=True, margins_name=总计名):获取行索引数据和行索引数据的交叉表(简单统计数量) ,显示总计行/列,默认名为All,可自定义总计名。
  • pd.crosstab(行索引数据, 行索引数据, dropna=False):获取行索引数据和行索引数据的交叉表(简单统计数量) 。整行都是NaN的也保留。

5、用于比较的函数

(5-1)比较数据的函数:lt, eq, ge等

DataFrame各元素可与数值和其他Series/DataFrame比较。

例如(小于):DataFrame.lt(self, other, axis='columns', level=None)

注:参数other:数值、序列(如:列表)、Series、另一个DataFrame。

  •  DataFrame.lt(other):DataFrame各元素与other比较,若符合比较条件,则相应位置为True,否则False。
DataFrame.lt(other)<less thanDataFrame各元素与other比较,若小于 则对应位置为True,否则为False
DataFrame.le(other)\leqless than or equalDataFrame各元素与other比较,若小于等于 则对应位置为True,否则为False
DataFrame.eq(other)=equalDataFrame各元素与other比较,若等于 则对应位置为True,否则为False
DataFrame.ne(other)\neqnot equalDataFrame各元素与other比较,若不等于 则对应位置为True,否则为False
DataFrame.gt(other)>greater thanDataFrame各元素与other比较,若大于 则对应位置为True,否则为False
DataFrame.ge(other)\geqgreater than or equalDataFrame各元素与other比较,若大于等于 则对应位置为True,否则为False

(5-2)两个DataFrame比较,返回不同的数据:compare

compare(self, other: 'DataFrame', align_axis: 'Axis' = 1, keep_shape: 'bool' = False, keep_equal: 'bool' = False) -> 'DataFrame'

  • DataFrame.compare(other):两个DataFrame比较,返回不同的数据。相同的默认显示NaN。默认self和other分别作为列索引显示。
  • DataFrame.compare(other, align_axis=0):两个DataFrame比较,返回不同的数据。相同的默认显示NaN。指定self和other分别作为行索引显示。
  • DataFrame.compare(other, keep_shape=True, keep_equal=True):两个DataFrame比较,返回不同的数据。相同的也显示。保留原形状。

(5-3) 比较两个DataFrame中的数据是否都相同:equals

equals(self, other: 'object') -> 'bool_t'

  • DataFrame.equals(另一个DataFrame):比较两个DataFrame中的数据是否都相同(对应数据类型也相同),都相同结果为True,否则False。若对应的数据类型不同,结果也为False。


6、应用一个函数:apply, applymap, map

(6-1)DataFrame/Series指定轴,应用一个函数:apply

apply(self, func: 'AggFuncType', axis: 'Axis' = 0, raw: 'bool' = False, result_type=None, args=(), **kwargs)

注:参数func:应用一个函数,函数后面不需要括号( )。参数args:元组形式,func的参数。

       参数axis:指定轴,默认axis=0 按行轴(各列)。

       参数result_type:结果显示。若元素是列表且axis=1可以扩展成多列。

  • DataFrame.apply(函数):各列元素依次应用函数,返回函数操作后结果。
  • DataFrame.apply(函数, args=函数参数):各列元素依次应用函数(函数参数以元组形式表示),返回函数操作后结果。

单列使用apply,可以依次判断元素。

DataFrame使用apply,默认指定轴,若指定轴中各行/列无法正确评估Series的值,则报错:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

可使用any或all或其他便于正确评估Series值。

添加一行总计和一列总计。 


(6-2)DataFrame每个元素,应用一个函数:applymap

applymap(self, func: 'PythonFuncType', na_action: 'str | None' = None, **kwargs) -> 'DataFrame'

  • DataFrame.applymap(函数):每个元素应用函数,每个元素返回各自对应的结果。
  • DataFrame.applymap(函数, 函数参数=值):每个元素应用函数(函数参数设定值),每个元素返回各自对应的结果。

 (6-3)Series每个元素,应用一个函数或映射:map

Series.map(self, arg, na_action=None) -> 'Series'

  • Series.map(函数或mapping或字典):Series每个元素应用函数或mapping,返回Series。

补充:apply, applymap, map

apply必要参数:函数用于DataFrame的各行或各列。也用于Series每个元素。
applymap必要参数:函数用于DataFrame每个元素。
map必要参数:函数或映射用于Series每个元素。


7、应用多个函数:transform, agg

(7-1)指定轴,应用多个函数转换数据:transform

transform(self, func: 'AggFuncType', axis: 'Axis' = 0, *args, **kwargs) -> 'DataFrame'

注:默认axis=0 按行(各列)转换。

  • DataFrame.transform(函数或字符串):各列按指定函数转换数据。
  • DataFrame.transform(列表):各列按列表中指定的多个函数转换数据。
  • DataFrame.transform(字典):各列按字典中对应的函数转换数据。字典中键为列名。字典中值为对应转换的函数,若值是列表,则指定列按多个函数转换数据。

transform可以和groupby一起使用。

DataFrameGroupBy.transform(func*argsengine=Noneengine_kwargs=None**kwargs)

  • DataFrame.groupby(分组列名)[转换列名].transform(函数):按分组列名分组后,指定转换列按组应用函数。

(7-2)指定轴,按多个函数聚合:agg

agg = aggregate(self, func=None, axis: 'Axis' = 0, *args, **kwargs)

aggregate(self, func=None, axis: 'Axis' = 0, *args, **kwargs)

agg是aggregate的别名。

  • DataFrame.agg(函数或字符串):各列按指定函数聚合。
  • DataFrame.agg(列表):各列按列表中指定的多个函数聚合。
  • DataFrame.agg(字典):各列按字典中对应的函数聚合。字典中键为列名。字典中值为函数,若值是列表,则指定列按多个函数聚合。

agg通常和groupby一起使用。

DataFrameGroupBy.agg(func=None*argsengine=Noneengine_kwargs=None**kwargs)

  • DataFrame.agg(分组列名).transform(函数):按分组列名分组后,按组按指定函数聚合。 


8、窗口函数:rolling, expanding, ewm

(8-1)移动窗口计算:rolling

rolling(self, window: 'int | timedelta | BaseOffset | BaseIndexer', min_periods: 'int | None' = None, center: 'bool_t' = False, win_type: 'str | None' = None, on: 'str | None' = None, axis: 'Axis' = 0, closed: 'str | None' = None, method: 'str' = 'single')

return : Window 或 Rolling

  • DataFrame.rolling(窗口大小):指定窗口大小依次向下移动计算,前几个不满足窗口大小的结果为NaN。
  • DataFrame.rolling(窗口大小, min_periods=最少数据):指定窗口大小依次向下移动计算,前几个虽不满足窗口大小但满足最少数据个数的的开始计算,既不满足窗口大小也不满足最少数据个数的结果为NaN。
  • DataFrame.rolling(窗口大小, min_periods=最少数据, center=True):指定窗口大小依次向下移动计算,前几个虽不满足窗口大小但满足最少数据个数的的也可以计算,既不满足窗口大小也不满足最少数据个数的结果为NaN。窗口居中。

rolling返回的结果,计算函数有限,例如:sum, max, count等。

 (具体参考:Window — pandas 2.2.2 documentation (pydata.org)

(8-2)扩展窗口计算:expanding

expanding(self, min_periods: 'int' = 1, center: 'bool_t | None' = None, axis: 'Axis' = 0, method: 'str' = 'single') -> 'Expanding'

  • DataFrame.expanding(最少数据):满足最少数据个数,就可以开始依次向下累积求和,前几个不满足最少数据个数的结果为NaN。
  • 注:参数center未来将被移除。

expanding返回的结果,计算函数有限,例如:sum, max, count等。

 (具体参考:Window — pandas 2.2.2 documentation (pydata.org)

(8-3)指数加权移动平均:ewm

加权移动平均:按不同权重求出移动平均值,并以最后的移动平均值确定预测值。

指数加权移动平均(EWMA):权重随时间呈指数级递减,越靠近当前时刻 数据的权重越大。指数加权移动平均法是常用的统计技术。

ewm(self, com: 'float | None' = None, span: 'float | None' = None, halflife: 'float | TimedeltaConvertibleTypes | None' = None, alpha: 'float | None' = None, min_periods: 'int | None' = 0, adjust: 'bool_t' = True, ignore_na: 'bool_t' = False, axis: 'Axis' = 0, times: 'str | np.ndarray | DataFrame | Series | None' = None, method: 'str' = 'single') -> 'ExponentialMovingWindow'

  • DataFrame.ewm(com=指定衰减因子):指数加权移动平均。α=1/(1+com)【注:com\geq0】。
  • DataFrame.ewm(span=指定时间跨度衰减因子):指数加权移动平均。α=2/(span+1)【注:span\geq1】。
  • DataFrame.ewm(alpha=直接指定平滑指数的衰减因子):指数加权移动平均。α【注:0<α\leq1】。
  • DataFrame.ewm(halflife=指定半衰期的衰减因子):指数加权移动平均。α=1-exp(-ln(2)/halflife)   【注:halflife>0】。
  • 注:参数adjust是否修正因子,默认adjust=True。

ewm返回的结果,计算函数有限,例如:mean, sum, std等。

 (具体参考:Window — pandas 2.2.2 documentation (pydata.org)


补充:

1、两个DataFrame应用函数合并列:combine

combine(self, other: 'DataFrame', func, fill_value=None, overwrite: 'bool' = True) -> 'DataFrame'

注:按元素合并列。

  • DataFrame.combine(另一个DataFrame,函数):两个DataFrame元素传入合并函数后,结果中行列索引为两个DataFrame的并集。
  • DataFrame.combine(另一个DataFrame,函数, filll_value=指定值):两个DataFrame元素传入合并函数后,结果中的行列索引为两个DataFrame的并集。使用指定值填充NaN。

2、判断元素是否存在:isin

isin(self, values) -> 'DataFrame'

注:参数values:可迭代对象(列表/元组等)、Series、DataFrame、字典(值不能是单个内容)。

  • DataFrame.isin(values):DataFrame中每个元素,依次判断是否是指定元素,若是则该位置为True,否则False,返回形状相同的DataFrame(数据为布尔值True/False)。
  • 注:values不能是单个内容。若values是字典,字典的值也不能是单个内容。否则报错:TypeError: only list-like or dict-like objects are allowed to be passed to DataFrame.isin(), you passed a 'int'。


pandas 各函数官方文档:General functions — pandas 2.2.2 documentation (pydata.org)

DataFrame 各方法官方文档:DataFrame — pandas 2.2.2 documentation (pydata.org)

Series 各方法官方文档:Series — pandas 2.2.2 documentation (pydata.org)

  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值