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 column

1 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.

Note

Despite 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.

Warning

The 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.

Warning

The 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、博客个人主页
  • 11
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神奇夜光杯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值