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中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

python删除xml中的w:ascii属性的步骤

《python删除xml中的w:ascii属性的步骤》使用xml.etree.ElementTree删除WordXML中w:ascii属性,需注册命名空间并定位rFonts元素,通过del操作删除属... 可以使用python的XML.etree.ElementTree模块通过以下步骤删除XML中的w:as

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

Python中Tensorflow无法调用GPU问题的解决方法

《Python中Tensorflow无法调用GPU问题的解决方法》文章详解如何解决TensorFlow在Windows无法识别GPU的问题,需降级至2.10版本,安装匹配CUDA11.2和cuDNN... 当用以下代码查看GPU数量时,gpuspython返回的是一个空列表,说明tensorflow没有找到