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删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核