案例 62: 计算累计统计量
知识点讲解
在数据分析中,计算累计统计量(如累计和、累计最大值、累计最小值等)是一种常见的操作。Pandas 提供了简单的方法来计算这些统计量。
- 计算累计统计量:
cumsum()
: 计算累计和。cummax()
: 计算累计最大值。cummin()
: 计算累计最小值。
示例代码
# 准备数据和示例代码的运行结果,用于案例 62# 示例数据
data_cumulative_stats = {'Values': [10, 20, 30, 40, 50]
}
df_cumulative_stats = pd.DataFrame(data_cumulative_stats)# 计算累计统计量
df_cumulative_stats['Cumulative Sum'] = df_cumulative_stats['Values'].cumsum()
df_cumulative_stats['Cumulative Max'] = df_cumulative_stats['Values'].cummax()
df_cumulative_stats['Cumulative Min'] = df_cumulative_stats['Values'].cummin()df_cumulative_stats
在这个示例中,我们计算了 Values
列的累计和、累计最大值和累计最小值。
示例代码运行结果
Values Cumulative Sum Cumulative Max Cumulative Min
0 10 10 10 10
1 20 30 20 10
2 30 60 30 10
3 40 100 40 10
4 50 150 50 10
这个结果展示了每步的累计统计量。累计统计量在分析时间序列数据或识别趋势时非常有用。