Python酷库之旅-第三方库Pandas(114)

2024-09-01 10:04

本文主要是介绍Python酷库之旅-第三方库Pandas(114),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

一、用法精讲

501、pandas.DataFrame.mode方法

501-1、语法

501-2、参数

501-3、功能

501-4、返回值

501-5、说明

501-6、用法

501-6-1、数据准备

501-6-2、代码示例

501-6-3、结果输出

502、pandas.DataFrame.pct_change方法

502-1、语法

502-2、参数

502-3、功能

502-4、返回值

502-5、说明

502-6、用法

502-6-1、数据准备

502-6-2、代码示例

502-6-3、结果输出

503、pandas.DataFrame.prod方法

503-1、语法

503-2、参数

503-3、功能

503-4、返回值

503-5、说明

503-6、用法

503-6-1、数据准备

503-6-2、代码示例

503-6-3、结果输出

504、pandas.DataFrame.product方法

504-1、语法

504-2、参数

504-3、功能

504-4、返回值

504-5、说明

504-6、用法

504-6-1、数据准备

504-6-2、代码示例

504-6-3、结果输出

505、pandas.DataFrame.quantile方法

505-1、语法

505-2、参数

505-3、功能

505-4、返回值

505-5、说明

505-6、用法

505-6-1、数据准备

505-6-2、代码示例

505-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

501、pandas.DataFrame.mode方法
501-1、语法
# 501、pandas.DataFrame.mode方法
pandas.DataFrame.mode(axis=0, numeric_only=False, dropna=True)
Get the mode(s) of each element along the selected axis.The mode of a set of values is the value that appears most often. It can be multiple values.Parameters:
axis
{0 or ‘index’, 1 or ‘columns’}, default 0
The axis to iterate over while searching for the mode:0 or ‘index’ : get mode of each column1 or ‘columns’ : get mode of each row.numeric_only
bool, default False
If True, only apply to numeric columns.dropna
bool, default True
Don’t consider counts of NaN/NaT.Returns:
DataFrame
The modes of each column or row.
501-2、参数

501-2-1、axis(可选,默认值为0){0或'index', 1或'columns'},0或'index',在行的方向上进行操作,计算每一列的众数;1或'columns',在列的方向上进行操作,计算每一行的众数。

501-2-2、numeric_only(可选,默认值为False)布尔值,如果为True,仅计算数值类型的列(或行)以寻找众数;如果为False,则所有类型的列(或行)都会被考虑。

501-2-3、dropna(可选,默认值为True)布尔值,是否在计算众数时忽略缺失值(NaN),如果为True,缺失值将被忽略;如果为False,则众数计算包括缺失值。

501-3、功能

        用于计算数据框中每一列或每一行的众数,即出现频率最高的值。

501-4、返回值

        返回一个DataFrame,其中每一列包含相应列(或行)的众数,如果有多个众数,返回的每个众数将占用不同的行。

501-5、说明

        无

501-6、用法
501-6-1、数据准备
501-6-2、代码示例
# 501、pandas.DataFrame.mode方法
import pandas as pd
# 创建一个示例数据框
data = {'A': [1, 2, 2, 3, 4],'B': [5, 5, 7, 7, 9],'C': [2, 4, None, 4, 10]
}
df = pd.DataFrame(data)
# 计算每列的众数
mode_values = df.mode(axis=0)
print("每列的众数:\n", mode_values)
# 计算每行的众数
mode_values_rows = df.mode(axis=1)
print("每行的众数:\n", mode_values_rows)
501-6-3、结果输出
# 501、pandas.DataFrame.mode方法
# 每列的众数:
#       A  B    C
# 0  2.0  5  4.0
# 1  NaN  7  NaN
# 每行的众数:
#       0    1     2
# 0  1.0  2.0   5.0
# 1  2.0  4.0   5.0
# 2  2.0  7.0   NaN
# 3  3.0  4.0   7.0
# 4  4.0  9.0  10.0
502、pandas.DataFrame.pct_change方法
502-1、语法
# 502、pandas.DataFrame.pct_change方法
pandas.DataFrame.pct_change(periods=1, fill_method=_NoDefault.no_default, limit=_NoDefault.no_default, freq=None, **kwargs)
Fractional change between the current and a prior element.Computes the fractional change from the immediately previous row by default. This is useful in comparing the fraction of change in a time series of elements.NoteDespite the name of this method, it calculates fractional change (also known as per unit change or relative change) and not percentage change. If you need the percentage change, multiply these values by 100.Parameters:
periodsint, default 1
Periods to shift for forming percent change.fill_method{‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default ‘pad’
How to handle NAs before computing percent changes.Deprecated since version 2.1: All options of fill_method are deprecated except fill_method=None.limitint, default None
The number of consecutive NAs to fill before stopping.Deprecated since version 2.1.freqDateOffset, timedelta, or str, optional
Increment to use from time series API (e.g. ‘ME’ or BDay()).**kwargs
Additional keyword arguments are passed into DataFrame.shift or Series.shift.Returns:
Series or DataFrame
The same type as the calling object.
502-2、参数

502-2-1、periods(可选,默认值为1)整数,表示计算变化的周期数。默认为1,即计算当前行与前一行的百分比变化;如果设置为2,则计算当前行与前两行的百分比变化,以此类推。

502-2-2、fill_method(可选)字符串,在计算过程中如何填充缺失值的方法,可以是'pad'(用前一个值填充)或'bfill'(用后一个值填充),如果不需要填充,可以省略此参数。

502-2-3、limit(可选)整数,指定在填充缺失值时的限制,表示最多填充的数量。

502-2-4、freq(可选,默认值为None)字符串,当处理时间序列数据时,可以用来定义频率,对于非时间序列数据,此参数无效。

502-2-5、**kwargs(可选)其他关键字参数,具体取决于具体实现。

502-3、功能

        用于计算数据框中每个元素与前一个元素之间的百分比变化,该方法对于时间序列数据分析非常有用,能够帮助你识别相对变化的趋势。

502-4、返回值

        返回一个新的DataFrame,其中包含每个元素相对于给定周期的百分比变化,数据框的维度与原始数据框相同,但首行或相应周期的行会含有NaN值,因为没有前一个值可供计算。

502-5、说明

        无

502-6、用法
502-6-1、数据准备
502-6-2、代码示例
# 502、pandas.DataFrame.pct_change方法
import pandas as pd
# 创建一个示例数据框
data = {'A': [100, 120, 150, 130],'B': [200, 220, 210, 250]
}
df = pd.DataFrame(data)
# 计算默认的百分比变化
pct_change_default = df.pct_change()
print("默认百分比变化:\n", pct_change_default)
# 计算周期为2的百分比变化
pct_change_periods_2 = df.pct_change(periods=2)
print("周期为2的百分比变化:\n", pct_change_periods_2)
502-6-3、结果输出
# 502、pandas.DataFrame.pct_change方法
# 默认百分比变化:
#            A         B
# 0       NaN       NaN
# 1  0.200000  0.100000
# 2  0.250000 -0.045455
# 3 -0.133333  0.190476
# 周期为2的百分比变化:
#            A         B
# 0       NaN       NaN
# 1       NaN       NaN
# 2  0.500000  0.050000
# 3  0.083333  0.136364
503、pandas.DataFrame.prod方法
503-1、语法
# 503、pandas.DataFrame.prod方法
pandas.DataFrame.prod(axis=0, skipna=True, numeric_only=False, min_count=0, **kwargs)
Return the product of the values over the requested axis.Parameters:
axis{index (0), columns (1)}
Axis for the function to be applied on. For Series this parameter is unused and defaults to 0.WarningThe behavior of DataFrame.prod with axis=None is deprecated, in a future version this will reduce over both axes and return a scalar To retain the old behavior, pass axis=0 (or do not pass axis).New in version 2.0.0.skipnabool, default True
Exclude NA/null values when computing the result.numeric_onlybool, default False
Include only float, int, boolean columns. Not implemented for Series.min_countint, default 0
The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.**kwargs
Additional keyword arguments to be passed to the function.Returns:
Series or scalar.
503-2、参数

503-2-1、axis(可选,默认值为0){0或 'index', 1或 'columns'},指定沿着哪个轴进行计算,0表示按列计算乘积,1表示按行计算乘积。

503-2-2、skipna(可选,默认值为True)布尔值,如果为True,则在计算乘积时会跳过缺失值(NaN);如果为False,缺失值将被视为0,从而使乘积结果为0。

503-2-3、numeric_only(可选,默认值为False)布尔值,如果为True,则只计算数值型列的乘积,非数值型列将被忽略。此参数在某些版本中可用,并可能在将来版本中更加严格。

503-2-4、min_count(可选,默认值为0)整数,指定计算乘积时所需的最小非缺失值数量,如果有效值数量少于min_count,则结果将为NaN。

503-2-5、**kwargs(可选)其他关键字参数,具体取决于具体实现。

503-3、功能

        用于计算数据框中元素的乘积,可以根据指定的轴进行操作,该方法在处理数值型数据时非常有用,特别是在需要计算总量或累积值的情况下。

503-4、返回值

        返回一个Series或标量值,表示所计算的乘积结果,如果沿着行计算,返回的Series将描述每列的乘积;如果沿着列计算,则返回标量值。

503-5、说明

        无

503-6、用法
503-6-1、数据准备
503-6-2、代码示例
# 503、pandas.DataFrame.prod方法
import pandas as pd
# 创建一个示例数据框
data = {'A': [1, 2, 3],'B': [4, 5, 6],'C': [7, None, 9]
}
df = pd.DataFrame(data)
# 计算按列的乘积
prod_columns = df.prod(axis=0)
print("按列计算的乘积:\n", prod_columns)
# 计算按行的乘积
prod_rows = df.prod(axis=1)
print("按行计算的乘积:\n", prod_rows)
# 跳过NaN值并计算乘积
prod_skipna = df.prod(skipna=True)
print("跳过NaN后的乘积:\n", prod_skipna)
# 设置min_count
prod_min_count = df.prod(min_count=2)
print("设置最小非缺失值计数后的乘积:\n", prod_min_count)
503-6-3、结果输出
# 503、pandas.DataFrame.prod方法
# 按列计算的乘积:
#  A      6.0
# B    120.0
# C     63.0
# dtype: float64
# 按行计算的乘积:
#  0     28.0
# 1     10.0
# 2    162.0
# dtype: float64
# 跳过NaN后的乘积:
#  A      6.0
# B    120.0
# C     63.0
# dtype: float64
# 设置最小非缺失值计数后的乘积:
#  A      6.0
# B    120.0
# C     63.0
# dtype: float64
504、pandas.DataFrame.product方法
504-1、语法
# 504、pandas.DataFrame.product方法
pandas.DataFrame.product(axis=0, skipna=True, numeric_only=False, min_count=0, **kwargs)
Return the product of the values over the requested axis.Parameters:
axis{index (0), columns (1)}
Axis for the function to be applied on. For Series this parameter is unused and defaults to 0.WarningThe behavior of DataFrame.prod with axis=None is deprecated, in a future version this will reduce over both axes and return a scalar To retain the old behavior, pass axis=0 (or do not pass axis).New in version 2.0.0.skipnabool, default True
Exclude NA/null values when computing the result.numeric_onlybool, default False
Include only float, int, boolean columns. Not implemented for Series.min_countint, default 0
The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.**kwargs
Additional keyword arguments to be passed to the function.Returns:
Series or scalar.
504-2、参数

504-2-1、axis(可选,默认值为0){0或 'index', 1或 'columns'},指定沿着哪个轴进行乘积计算,0表示按行计算(每列的乘积),1表示按列计算(每行的乘积)。

504-2-2、skipna(可选,默认值为True)布尔值,是否在计算乘积时跳过缺失值(NaN),如果设置为True,缺失值将被忽略;如果为False,缺失值将会导致结果为NaN。

504-2-3、numeric_only(可选,默认值为False)布尔值,如果为True,仅计算数值类型的列;如果为False,所有列都会被考虑,但非数值列会对计算产生影响。

504-2-4、min_count(可选,默认值为0)整数,在计算乘积时,至少需要的非缺失值数量,如果有效值数量少于这个值,结果将为NaN。

504-2-5、**kwargs(可选)其他关键字参数,具体实现上可能会有不同的效果。

504-3、功能

        用于计算数据框中元素的乘积,可以按指定的轴进行操作。

504-4、返回值

        返回一个Series或标量值,表示乘积结果,如果按行计算,返回的Series会表示每列的乘积;若按列计算,则返回一个标量值。

504-5、说明

        无

504-6、用法
504-6-1、数据准备
504-6-2、代码示例
# 504、pandas.DataFrame.product方法
import pandas as pd
# 创建示例数据框
data = {'A': [1, 2, 3],'B': [4, 5, 6],'C': [7, None, 9]  # 包含一个 NaN 值
}
df = pd.DataFrame(data)
# 计算按列的乘积
prod_columns = df.product(axis=0)
print("按列计算的乘积:\n", prod_columns)
# 计算按行的乘积
prod_rows = df.product(axis=1)
print("按行计算的乘积:\n", prod_rows)
# 跳过NaN值并计算乘积
prod_skipna = df.product(skipna=True)
print("跳过 NaN 后的乘积:\n", prod_skipna)
# 设置min_count
prod_min_count = df.product(min_count=2)
print("设置最小非缺失值计数后的乘积:\n", prod_min_count)
# 计算数值类型的乘积
prod_numeric_only = df.product(numeric_only=True)
print("只计算数值类型的乘积:\n", prod_numeric_only)
504-6-3、结果输出
# 504、pandas.DataFrame.product方法
# 按列计算的乘积:
#  A      6.0
# B    120.0
# C     63.0
# dtype: float64
# 按行计算的乘积:
#  0     28.0
# 1     10.0
# 2    162.0
# dtype: float64
# 跳过 NaN 后的乘积:
#  A      6.0
# B    120.0
# C     63.0
# dtype: float64
# 设置最小非缺失值计数后的乘积:
#  A      6.0
# B    120.0
# C     63.0
# dtype: float64
# 只计算数值类型的乘积:
#  A      6.0
# B    120.0
# C     63.0
# dtype: float64
505、pandas.DataFrame.quantile方法
505-1、语法
# 505、pandas.DataFrame.quantile方法
pandas.DataFrame.quantile(q=0.5, axis=0, numeric_only=False, interpolation='linear', method='single')
Return values at the given quantile over requested axis.Parameters:
qfloat or array-like, default 0.5 (50% quantile)
Value between 0 <= q <= 1, the quantile(s) to compute.axis{0 or ‘index’, 1 or ‘columns’}, default 0
Equals 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise.numeric_onlybool, default False
Include only float, int or boolean data.Changed in version 2.0.0: The default value of numeric_only is now False.interpolation{‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}
This optional parameter specifies the interpolation method to use, when the desired quantile lies between two data points i and j:linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.lower: i.higher: j.nearest: i or j whichever is nearest.midpoint: (i + j) / 2.method{‘single’, ‘table’}, default ‘single’
Whether to compute quantiles per-column (‘single’) or over all columns (‘table’). When ‘table’, the only allowed interpolation methods are ‘nearest’, ‘lower’, and ‘higher’.Returns:
Series or DataFrame
If
q
is an array, a DataFrame will be returned where the
index is q, the columns are the columns of self, and the values are the quantiles.If
q
is a float, a Series will be returned where the
index is the columns of self and the values are the quantiles.
505-2、参数

505-2-1、q(可选,默认值为0.5)浮点数或类数组对象,要计算的分位数,范围在[0, 1]之间,可传入多个分位数(如[0.25,0.5,0.75])来获取相应的分位值,默认值为0.5(中位数)。

505-2-2、axis(可选,默认值为0){0或 'index', 1或 'columns'},指定计算的轴,0表示按列计算(计算每一列的分位数),1表示按行计算(计算每一行的分位数)。

505-2-3、numeric_only(可选,默认值为False)布尔值,如果为True,仅计算数值类型的列;如果为False,所有列都会被考虑,但非数值类型的列会为结果带来影响。

505-2-4、interpolation(可选,默认值为'linear'){‘linear’, ‘lower’, ‘higher’, ‘nearest’, ‘midpoint’, ‘slinear’, ‘spline’, ‘barycentric’},指定用于计算分位数的插值方法,当数据点不足以找到q分位数时,这将影响计算结果。

505-2-5、method(可选,默认值为'single'){‘single’, ‘pandas’},指定用于计算方法的选择,'single'表示直接取中位数或分位数,'pandas'会基于pandas的实现进行计算。

505-3、功能

        用于计算数据框中指定分位数的值。

505-4、返回值

        返回一个Series或标量值,表示指定分位数的结果,如果按行计算,返回的结果将会是一个Series,其中包含每一行的分位值。

505-5、说明

        无

505-6、用法
505-6-1、数据准备
505-6-2、代码示例
# 505、pandas.DataFrame.quantile方法
import pandas as pd
# 创建示例数据框
data = {'A': [1, 2, 3, 4, 5],'B': [5, 6, 7, 8, 9],'C': [10, 15, 20, 25, 30]
}
df = pd.DataFrame(data)
# 计算中位数
median = df.quantile(q=0.5)
print("中位数:\n", median)
# 计算第25和75百分位数
quantiles_25_75 = df.quantile(q=[0.25, 0.75])
print("第25和75百分位数:\n", quantiles_25_75)
# 按行计算分位数
row_quantile = df.quantile(q=0.5, axis=1)
print("按行计算中位数:\n", row_quantile)
# 只计算数值类型的分位数
numeric_quantile = df.quantile(numeric_only=True)
print("只计算数值类型的分位数:\n", numeric_quantile)
# 使用不同的插值方法计算分位数
interpolation_quantile = df.quantile(q=0.5, interpolation='midpoint')
print("使用中点插值法计算中位数:\n", interpolation_quantile)
505-6-3、结果输出
# 505、pandas.DataFrame.quantile方法
# 中位数:
#  A     3.0
# B     7.0
# C    20.0
# Name: 0.5, dtype: float64
# 第25和75百分位数:
#          A    B     C
# 0.25  2.0  6.0  15.0
# 0.75  4.0  8.0  25.0
# 按行计算中位数:
#  0    5.0
# 1    6.0
# 2    7.0
# 3    8.0
# 4    9.0
# Name: 0.5, dtype: float64
# 只计算数值类型的分位数:
#  A     3.0
# B     7.0
# C    20.0
# Name: 0.5, dtype: float64
# 使用中点插值法计算中位数:
#  A     3.0
# B     7.0
# C    20.0
# Name: 0.5, dtype: float64

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页

这篇关于Python酷库之旅-第三方库Pandas(114)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1126623

相关文章

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

一文详解Python如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D

Python函数作用域与闭包举例深度解析

《Python函数作用域与闭包举例深度解析》Python函数的作用域规则和闭包是编程中的关键概念,它们决定了变量的访问和生命周期,:本文主要介绍Python函数作用域与闭包的相关资料,文中通过代码... 目录1. 基础作用域访问示例1:访问全局变量示例2:访问外层函数变量2. 闭包基础示例3:简单闭包示例4

Python实现字典转字符串的五种方法

《Python实现字典转字符串的五种方法》本文介绍了在Python中如何将字典数据结构转换为字符串格式的多种方法,首先可以通过内置的str()函数进行简单转换;其次利用ison.dumps()函数能够... 目录1、使用json模块的dumps方法:2、使用str方法:3、使用循环和字符串拼接:4、使用字符

Python版本与package版本兼容性检查方法总结

《Python版本与package版本兼容性检查方法总结》:本文主要介绍Python版本与package版本兼容性检查方法的相关资料,文中提供四种检查方法,分别是pip查询、conda管理、PyP... 目录引言为什么会出现兼容性问题方法一:用 pip 官方命令查询可用版本方法二:conda 管理包环境方法

基于Python开发Windows自动更新控制工具

《基于Python开发Windows自动更新控制工具》在当今数字化时代,操作系统更新已成为计算机维护的重要组成部分,本文介绍一款基于Python和PyQt5的Windows自动更新控制工具,有需要的可... 目录设计原理与技术实现系统架构概述数学建模工具界面完整代码实现技术深度分析多层级控制理论服务层控制注

pycharm跑python项目易出错的问题总结

《pycharm跑python项目易出错的问题总结》:本文主要介绍pycharm跑python项目易出错问题的相关资料,当你在PyCharm中运行Python程序时遇到报错,可以按照以下步骤进行排... 1. 一定不要在pycharm终端里面创建环境安装别人的项目子模块等,有可能出现的问题就是你不报错都安装

Python打包成exe常用的四种方法小结

《Python打包成exe常用的四种方法小结》本文主要介绍了Python打包成exe常用的四种方法,包括PyInstaller、cx_Freeze、Py2exe、Nuitka,文中通过示例代码介绍的非... 目录一.PyInstaller11.安装:2. PyInstaller常用参数下面是pyinstal

Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题

《Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题》在爬虫工程里,“HTTPS”是绕不开的话题,HTTPS为传输加密提供保护,同时也给爬虫带来证书校验、... 目录一、核心问题与优先级检查(先问三件事)二、基础示例:requests 与证书处理三、高并发选型:

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数