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

目录

一、用法精讲

161、pandas.Series.cumsum方法

161-1、语法

161-2、参数

161-3、功能

161-4、返回值

161-5、说明

161-6、用法

161-6-1、数据准备

161-6-2、代码示例

161-6-3、结果输出

162、pandas.Series.describe方法

162-1、语法

162-2、参数

162-3、功能

162-4、返回值

162-5、说明

162-6、用法

162-6-1、数据准备

162-6-2、代码示例

162-6-3、结果输出

163、pandas.Series.diff方法

163-1、语法

163-2、参数

163-3、功能

163-4、返回值

163-5、说明

163-6、用法

163-6-1、数据准备

163-6-2、代码示例

163-6-3、结果输出

164、pandas.Series.factorize方法

164-1、语法

164-2、参数

164-3、功能

164-4、返回值

164-5、说明

164-6、用法

164-6-1、数据准备

164-6-2、代码示例

164-6-3、结果输出

165、pandas.Series.kurt方法

165-1、语法

165-2、参数

165-3、功能

165-4、返回值

165-5、说明

165-6、用法

165-6-1、数据准备

165-6-2、代码示例

165-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

161、pandas.Series.cumsum方法
161-1、语法
# 161、pandas.Series.cumsum方法
pandas.Series.cumsum(axis=None, skipna=True, *args, **kwargs)
Return cumulative sum over a DataFrame or Series axis.

Returns a DataFrame or Series of the same size containing the cumulative sum.

Parameters:
axis
{0 or ‘index’, 1 or ‘columns’}, default 0
The index or the name of the axis. 0 is equivalent to None or ‘index’. For Series this parameter is unused and defaults to 0.

skipna
bool, default True
Exclude NA/null values. If an entire row/column is NA, the result will be NA.

*args, **kwargs
Additional keywords have no effect but might be accepted for compatibility with NumPy.

Returns:
scalar or Series
Return cumulative sum of scalar or Series.
161-2、参数

161-2-1、axis(可选,默认值为None)对于Series,这个参数不需要使用。

161-2-2、skipna(可选,默认值为True)如果设置为True,则在计算时会忽略NaN值;如果设置为False,则一旦遇到NaN,之后的结果也会是NaN。

161-2-3、*args(可选)其他位置参数,这里通常不需要使用。

161-2-4、**kwargs(可选)其他关键字参数,通常也不使用于此方法。

161-3、功能

        用于计算累积和的方法,它返回一个新的系列,其中每个元素都是原系列中该位置之前所有元素的总和。

161-4、返回值

        返回一个新的Series,其中包含了累积和的结果。

161-5、说明

        应用场景:

161-5-1时间序列分析:在金融数据中,比如股票价格或销售额,累积和可以帮助分析某个时间段内的总收益或总销售量。

161-5-2、数据统计:在进行数据分析时,可以使用累积和来跟踪某个变量的增长趋势。例如,分析一天内的访客数量时,可以通过计算每小时的累积访问量来了解高峰时段。

161-5-3、分组数据分析:在处理分组数据时,例如按类别或组别计算累积总和,可以帮助比较不同组的累计情况。

161-5-4、滚动计算:在某些情况下,需使用累积和来计算滚动窗口的总和,或用作其他派生指标的基础。

161-5-5、日志分析:在对日志数据进行分析时,可以用累积和来追踪事件发生的频率,比如错误数量的积累。

161-6、用法
161-6-1、数据准备
161-6-2、代码示例
# 161、pandas.Series.cumsum方法
import pandas as pd
# 创建一个示例Series
s = pd.Series([1, 2, 3, 4, 5])
# 计算累积和
cumulative_sum = s.cumsum()
print(cumulative_sum)
161-6-3、结果输出
# 161、pandas.Series.cumsum方法
# 0     1
# 1     3
# 2     6
# 3    10
# 4    15
# dtype: int64
162、pandas.Series.describe方法
162-1、语法
# 162、pandas.Series.describe方法
pandas.Series.describe(percentiles=None, include=None, exclude=None)
Generate descriptive statistics.

Descriptive statistics include those that summarize the central tendency, dispersion and shape of a dataset’s distribution, excluding NaN values.

Analyzes both numeric and object series, as well as DataFrame column sets of mixed data types. The output will vary depending on what is provided. Refer to the notes below for more detail.

Parameters:
percentiles
list-like of numbers, optional
The percentiles to include in the output. All should fall between 0 and 1. The default is [.25, .5, .75], which returns the 25th, 50th, and 75th percentiles.

include
‘all’, list-like of dtypes or None (default), optional
A white list of data types to include in the result. Ignored for Series. Here are the options:

‘all’ : All columns of the input will be included in the output.

A list-like of dtypes : Limits the results to the provided data types. To limit the result to numeric types submit numpy.number. To limit it instead to object columns submit the numpy.object data type. Strings can also be used in the style of select_dtypes (e.g. df.describe(include=['O'])). To select pandas categorical columns, use 'category'

None (default) : The result will include all numeric columns.

exclude
list-like of dtypes or None (default), optional,
A black list of data types to omit from the result. Ignored for Series. Here are the options:

A list-like of dtypes : Excludes the provided data types from the result. To exclude numeric types submit numpy.number. To exclude object columns submit the data type numpy.object. Strings can also be used in the style of select_dtypes (e.g. df.describe(exclude=['O'])). To exclude pandas categorical columns, use 'category'

None (default) : The result will exclude nothing.

Returns:
Series or DataFrame
Summary statistics of the Series or Dataframe provided.
162-2、参数

162-2-1、percentiles(可选,默认值为None)指定要计算的分位数。可以传入一个包含0到1之间浮点数的列表,例如[0.25, 0.5, 0.75]表示计算25%、50%和75%的分位数。如果不指定,默认会计算25%、50%(中位数)和75%分位数。

162-2-2、include(可选,默认值为None)表示指定要包括的描述性统计数据类型,可以是以下内容之一:

162-2-2-1、'number':包括数值型数据。

162-2-2-2、'object':包括字符串或其他对象数据。

162-2-2-3、'category':包括分类数据。

162-2-2-4、也可以使用列表形式,例如['number', 'object']。默认情况下,如果此参数为 None,将包括所有数据类型。

162-2-3、exclude(可选,默认值为None)指定要排除的描述性统计数据类型。可以是与include参数相同的类型。比如,如果希望排除字符串类型数据,可以传入['object']。同样,如果为None,将不排除任何类型。

162-3、功能

        该方法主要用于:

162-3-1、计算基本统计量,例如计数、均值、标准差、最小值、最大值和分位数等。

162-3-2、分析数据的分布情况,提供数值型和分类型数据的基本信息。

162-4、返回值

        返回一个Series或DataFrame,具体取决于输入数据的类型和所选择的统计信息,返回内容通常包括以下几项:

162-4-1、count:数据点的数量。

162-4-2、mean:均值(针对数值型数据)。

162-4-3、std:标准差(针对数值型数据)。

162-4-4、min:最小值。

162-4-5、25%:25%的分位数(第一四分位数)。

162-4-6、50%:中位数(第二四分位数)。

162-4-7、75%:75%的分位数(第三四分位数)。

162-4-8、max:最大值。

162-4-9、对于对象类型(如字符串),返回的数据将会是计数、唯一值数量、最常见的值及其频率。

162-5、说明

        应用场景:

162-5-1、数据解析:快速获得数据的汇总信息。

162-5-2、数据清洗:分析缺失值和异常值的情况。

162-5​​​​​​​-3、探索性数据分析:分析数据分布,以便做出进一步的数据分析和决策。

162-6、用法
162-6-1、数据准备
162-6-2、代码示例
# 162、pandas.Series.describe方法
# 162-1、默认使用describe(),计算默认的统计信息
import pandas as pd
# 创建一个示例Series
data = pd.Series([3, 5, 6, 8, 10, 10, 11, 24])
print(data.describe(), end='\n\n')

# 162-2、自定义分位数
import pandas as pd
# 创建一个示例Series
data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(data.describe(percentiles=[0.1, 0.5, 0.9]), end='\n\n')

# 162-3、仅包括数值型统计信息
import pandas as pd
# 创建一个示例Series
data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(data.describe(include='number'), end='\n\n')

# 162-4、排除对象类型(如果有的话)
import pandas as pd
# 创建一个示例Series
data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(data.describe(exclude='object'))
162-6-3、结果输出
# 162、pandas.Series.describe方法
# 162-1、默认使用describe(),计算默认的统计信息
# count     8.000000
# mean      9.625000
# std       6.435116
# min       3.000000
# 25%       5.750000
# 50%       9.000000
# 75%      10.250000
# max      24.000000
# dtype: float64

# 162-2、自定义分位数
# count    10.00000
# mean      5.50000
# std       3.02765
# min       1.00000
# 10%       1.90000
# 50%       5.50000
# 90%       9.10000
# max      10.00000
# dtype: float64

# 162-3、仅包括数值型统计信息
# count    10.00000
# mean      5.50000
# std       3.02765
# min       1.00000
# 25%       3.25000
# 50%       5.50000
# 75%       7.75000
# max      10.00000
# dtype: float64

# 162-4、排除对象类型(如果有的话)
# count    10.00000
# mean      5.50000
# std       3.02765
# min       1.00000
# 25%       3.25000
# 50%       5.50000
# 75%       7.75000
# max      10.00000
# dtype: float64
163、pandas.Series.diff方法
163-1、语法
# 163、pandas.Series.diff方法
pandas.Series.diff(periods=1)
First discrete difference of element.

Calculates the difference of a Series element compared with another element in the Series (default is element in previous row).

Parameters:
periods
int, default 1
Periods to shift for calculating difference, accepts negative values.

Returns:
Series
First differences of the Series.
163-2、参数

163-2-1、periods(可选,默认值为1)一个整数,用于指定计算差分时所考虑的周期数。如果periods为 1,将计算当前元素与前一个元素之间的差值;如果periods为 2,将计算当前元素与前两个元素之前的差值;以此类推。可以是正数或负数,负数会向前看,比如-1会计算当前元素与下一个元素之间的差值。

163-3、功能

        用于计算当前系列元素与前一个元素(或指定周期的元素)之间的差值。它的主要功能是在时间序列分析中帮助识别变化和趋势。

163-4、返回值

        返回一个与原始系列长度相同的新系列,差分后的前periods个元素将为NaN(因为没有数据可供计算)。

163-5、说明

        该方法在各种数据分析和时间序列分析场景中非常有用。以下是一些常见的应用场景:

163-5-1、趋势分析:通过计算数据的差分,帮助识别时间序列中的趋势和模式。如分析股票价格的变化,以确定价格的上升或下降趋势。

163-5-2、季节性调整:在时间序列数据中识别和调整季节性波动。如对月度销售数据进行差分处理,以去除季节性波动的影响,从而更好地识别销售的长期趋势。

163-5-3、数据平稳化:将非平稳的时间序列数据转换为平稳数据,以便进行进一步的分析和建模。如在进行时间序列预测模型(如ARIMA模型)之前,通过差分将数据的非平稳性去除。

163-5-4、异常检测:通过计算数据点之间的差异,帮助发现异常值或突发事件。如监控传感器数据的差分来检测设备故障或异常变化。

163-5-5、收益率计算:计算金融数据中的收益率。如计算股票或基金的日收益率,以评估投资表现。

163-5-6、信号处理:在信号处理领域,使用差分方法来增强或减弱信号的特定部分。如在处理音频信号时,计算信号的差分以突出变化部分,辅助进一步的分析或处理。

163-6、用法
163-6-1、数据准备
163-6-2、代码示例
# 163、pandas.Series.diff方法
# 163-1、计算与前一个元素的差值
import pandas as pd
# 创建一个示例Series
data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
diff_1 = data.diff()
print(diff_1, end='\n\n')

# 163-2、计算与前两个元素的差值
import pandas as pd
# 创建一个示例Series
data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
diff_2 = data.diff(periods=2)
print(diff_2, end='\n\n')

# 163-3、计算与下一个元素的差值
import pandas as pd
# 创建一个示例Series
data = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
diff_neg = data.diff(periods=-1)
print(diff_neg)
163-6-3、结果输出
# 163、pandas.Series.diff方法
# 163-1、计算与前一个元素的差值
# 0    NaN
# 1    1.0
# 2    1.0
# 3    1.0
# 4    1.0
# 5    1.0
# 6    1.0
# 7    1.0
# 8    1.0
# 9    1.0
# dtype: float64

# 163-2、计算与前两个元素的差值
# 0    NaN
# 1    NaN
# 2    2.0
# 3    2.0
# 4    2.0
# 5    2.0
# 6    2.0
# 7    2.0
# 8    2.0
# 9    2.0
# dtype: float64

# 163-3、计算与下一个元素的差值
# 0   -1.0
# 1   -1.0
# 2   -1.0
# 3   -1.0
# 4   -1.0
# 5   -1.0
# 6   -1.0
# 7   -1.0
# 8   -1.0
# 9    NaN
# dtype: float64
164、pandas.Series.factorize方法
164-1、语法
# 164、pandas.Series.factorize方法
pandas.Series.factorize(sort=False, use_na_sentinel=True)
Encode the object as an enumerated type or categorical variable.

This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. factorize is available as both a top-level function pandas.factorize(), and as a method Series.factorize() and Index.factorize().

Parameters:
sortbool, default False
Sort uniques and shuffle codes to maintain the relationship.

use_na_sentinelbool, default True
If True, the sentinel -1 will be used for NaN values. If False, NaN values will be encoded as non-negative integers and will not drop the NaN from the uniques of the values.

New in version 1.5.0.

Returns:
codesndarray
An integer ndarray that’s an indexer into uniques. uniques.take(codes) will have the same values as values.

uniquesndarray, Index, or Categorical
The unique valid values. When values is Categorical, uniques is a Categorical. When values is some other pandas object, an Index is returned. Otherwise, a 1-D ndarray is returned.

Note

Even if there’s a missing value in values, uniques will not contain an entry for it.
164-2、参数

164-2-1、sort(可选,默认值为False)如果设置为True,输出的唯一值数组会被排序。

164-2-2、use_na_sentinel(可选,默认值为True)如果设置为True,缺失值(NaN)将被分配为一个特殊的整数值,通常是-1;如果设置为False,缺失值将不会被标记。

164-3、功能

        用于将系列的值编码为整数的函数,它可以将非唯一的值转换为一个整数数组,这些整数代表了不同的唯一值,同时还返回唯一值的数组。

164-4、返回值

        返回一个元组,包含两个元素:

164-4-1、一个整数数组,表示每个原始值的编码。

164-4-2、一个包含唯一值的数组。

164-5、说明

        应用场景:

164-5-1、类别变量编码: 在机器学习中,许多算法要求输入特征是数值型的,使用factorize可以将类别变量(如字符串标签)转换为整型编码,以便可以直接用于模型训练。

164-5-2、数据预处理: 在数据清洗和预处理过程中,常常需要将重复的文本或分类数据转化为唯一值并编码,通过factorize可以高效地实现这一点。

164-5-3、去重和性能优化: 通过将类别变量转化为整数编码,可以减少内存使用和提高计算性能,尤其是在处理大数据集时。

164-5-4、处理缺失值: 提供use_na_sentinel参数以便于处理包含缺失数据的情况,使得对缺失值进行统一编码,便于后续分析。

164-5-5、分析数据分布: 使用factorize可以帮助分析数据中不同类别的分布情况,例如,了解数据集中不同类别的数量和类型。

164-5​​​​​​​-6、生成标签: 在需要为每个类别生成标签或索引时,例如用于绘图或数据可视化。

164-6、用法
164-6-1、数据准备
164-6-2、代码示例
# 164、pandas.Series.factorize方法
# 164-1、类别变量编码
import pandas as pd
# 创建一个示例数据集
data = pd.Series(['apple', 'banana', 'apple', 'orange', 'banana', 'orange', 'apple'])
# 使用factorize进行编码
codes, uniques = data.factorize()
# 输出编码结果和唯一值
print("编码结果:", codes)
print("唯一值:", uniques, end='\n\n')

# 164-2、处理缺失值
import pandas as pd
# 创建一个包含缺失值的示例数据集
data = pd.Series(['red', 'blue', None, 'green', 'blue', None])
# 使用factorize进行编码,并处理缺失值
codes, uniques = data.factorize(use_na_sentinel=True)
# 输出编码结果和唯一值
print("编码结果:", codes)
print("唯一值:", uniques, end='\n\n')

# 164-3、数据预处理与特征工程
import pandas as pd
# 创建一个示例数据集
data = pd.DataFrame({
    'fruit': ['apple', 'banana', 'apple', 'orange', 'banana', 'orange'],
    'color': ['red', 'yellow', 'red', 'orange', 'yellow', 'orange']
})
# 对'fruit'列进行编码
data['fruit_code'], uniques_fruit = data['fruit'].factorize()
# 对'color'列进行编码
data['color_code'], uniques_color = data['color'].factorize()
# 输出处理后的数据集
print(data, end='\n\n')

# 164-4、数据探索性分析
import pandas as pd
# 创建一个示例数据集
data = pd.Series(['dog', 'cat', 'dog', 'bird', 'cat', 'dog'])
# 使用factorize进行编码
codes, uniques = data.factorize()
# 将编码结果转换为DataFrame
df = pd.DataFrame({'animal': uniques, 'code': range(len(uniques))})
# 统计每种动物出现的次数
count_series = data.value_counts()
# 输出频数统计
print("动物频数统计:\n", count_series)
# 输出编码结果
print("编码结果:\n", df)
164-6-3、结果输出
# 164、pandas.Series.factorize方法
# 164-1、类别变量编码
# 编码结果: [0 1 0 2 1 2 0]
# 唯一值: Index(['apple', 'banana', 'orange'], dtype='object')

# 164-2、处理缺失值
# 编码结果: [ 0  1 -1  2  1 -1]
# 唯一值: Index(['red', 'blue', 'green'], dtype='object')

# 164-3、数据预处理与特征工程
#     fruit   color  fruit_code  color_code
# 0   apple     red           0           0
# 1  banana  yellow           1           1
# 2   apple     red           0           0
# 3  orange  orange           2           2
# 4  banana  yellow           1           1
# 5  orange  orange           2           2

# 164-4、数据探索性分析
# 动物频数统计:
#  dog     3
# cat     2
# bird    1
# Name: count, dtype: int64
# 编码结果:
#    animal  code
# 0    dog     0
# 1    cat     1
# 2   bird     2
165、pandas.Series.kurt方法
165-1、语法
# 165、pandas.Series.kurt方法
pandas.Series.kurt(axis=0, skipna=True, numeric_only=False, **kwargs)
Return unbiased kurtosis over requested axis.

Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1.

Parameters:
axis{index (0)}
Axis for the function to be applied on. For Series this parameter is unused and defaults to 0.

For DataFrames, specifying axis=None will apply the aggregation across both axes.

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.

**kwargs
Additional keyword arguments to be passed to the function.

Returns:
scalar or scalar
165-2、参数

165-2-1、axis(可选,默认值为0)表示沿着指定的轴计算。

165-2-2、skipna(可选,默认值为True)是否跳过缺失值(NaN),如果为False,则在存在缺失值时结果为NaN。

165-2-3、numeric_only(可选,默认值为False)用于指示是否仅计算数值数据类型。

165-2-4、**kwargs(可选)其他关键字参数。

165-3、功能

        用于计算数据的峰度(Kurtosis),即描述数据分布形态的一种统计量,其中,峰度反映了数据的尖峭程度或平坦程度。

165-4、返回值

        返回一个浮点数,表示峰度值,若存在缺失值且未跳过,则返回NaN。

165-5、说明

        应用场景:

165-5-1、金融数据分析:在金融领域,峰度用于分析资产回报率的分布特征,高峰度可能表明事件发生的概率比正态分布更高,如极端收益或损失,帮助投资者评估风险。

165-5-2、风险管理:峰度可以用于风险管理中的极值理论(Extreme Value Theory),识别潜在的尾部风险(tail risk),高峰度的分布意味着极端值的出现更为频繁,可能需要采取额外的风险控制措施。

165-5-3、市场营销分析:在客户行为分析中,峰度可以用于评估客户支出的分布,如果支出分布的峰度较高,可能意味着大部分消费者的支出集中在某些特定的区间,这为制定营销策略提供了依据。

165-5-4、科学研究和工程:在实验数据分析中,峰度可用于评估实验结果的异常值或数据质量,通过观察峰度,研究人员可以识别数据的偏离程度,从而进行更深入的研究。

165-5-5、机器学习特征工程:在特征选择过程中,峰度可作为一种特征,从而帮助模型区分不同类型的数据分布,这有助于提高模型的性能,通过反映数据的分布特征来增强分类或回归模型。

165-5-6、质量控制:在制造和质量控制中,通过监控生产过程的峰度,可以评估产品质量的稳定性,如果产品尺寸或特性的数据分布峰度异常,可能需要调整生产工艺。

165-5-7、社会科学研究:在社会科学领域,峰度可以用于分析调查数据的分布特征,从而了解特定变量在某种特性(如收入、教育水平等)上的集中程度。

165-6、用法
165-6-1、数据准备
165-6-2、代码示例
# 165、pandas.Series.kurt方法
# 165-1、计算基本峰度
import pandas as pd
# 创建一个示例数据集
data = pd.Series([1, 2, 3, 4, 5])
# 计算峰度
kurtosis = data.kurt()
print("峰度:", kurtosis, end='\n\n')

# 165-2、跳过缺失值
import pandas as pd
import numpy as np
# 创建一个包含缺失值的示例数据集
data = pd.Series([1, 2, np.nan, 4, 5])
# 计算峰度,跳过缺失值
kurtosis = data.kurt(skipna=True)
print("跳过缺失值后的峰度:", kurtosis, end='\n\n')
165-6-3、结果输出
# 165、pandas.Series.kurt方法
# 165-1、计算基本峰度
# 峰度: -1.2000000000000002

# 165-2、跳过缺失值
# 跳过缺失值后的峰度: -3.3000000000000007

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页
  • 47
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 26
    评论
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

神奇夜光杯

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

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

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

打赏作者

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

抵扣说明:

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

余额充值