欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 详解 Pandas 的累计统计函数

详解 Pandas 的累计统计函数

2024/10/25 19:33:49 来源:https://blog.csdn.net/weixin_44480009/article/details/142302323  浏览:    关键词:详解 Pandas 的累计统计函数

Pandas 中常用的累计统计函数有 cumsum()cummax()cummin()cumprod(),分别是用来统计 DataFrame 中按行或按列的累加值、累计最大值、累计最小值、累乘值。

一、数据准备

import pandas as pddf = pd.DataFrame(data={'Product_A': [100, 300, 200, 250, 300],'Product_B': [50, 100, 350, 200, 250]
}, index=['1月', '2月', '3月', '4月', '5月'])print(df)
     Product_A  Product_B
1月        100         50
2月        300        100
3月        200        350
4月        250        200
5月        300        250

二、cumsum 函数

统计从第一行(列)到当前行(列)的累加,类似于 SQL 中的 sum() over() 窗口函数

# 1.沿行轴统计累加
print(df.cumsum())  # df.cumsum(axis=0)
   Product_A  Product_B
1月        100         50
2月        400        150
3月        600        500
4月        850        700
5月       1150        950
# 2.沿列轴统计累加
print(df.cumsum(axis=1))
    Product_A  Product_B
1月        100        150
2月        300        400
3月        200        550
4月        250        450
5月        300        550

三、cummax 函数

统计从第一行(列)到当前行(列)中的最大值,类似于 SQL 中的 max() over() 窗口函数

# 1.沿行轴统计累计最大值
print(df.cummax())
    Product_A  Product_B
1月        100         50
2月        300        100
3月        300        350
4月        300        350
5月        300        350
# 2.沿列轴统计累计最大值
print(df.cummax(axis=1))
    Product_A  Product_B
1月        100        100
2月        300        300
3月        200        350
4月        250        250
5月        300        300

四、cummin 函数

统计从第一行(列)到当前行(列)中的最小值,类似于 SQL 中的 min() over() 窗口函数

# 1.沿行轴统计累计最小值
print(df.cummin())
     Product_A  Product_B
1月        100         50
2月        100         50
3月        100         50
4月        100         50
5月        100         50
# 2.沿列轴统计累计最小值
print(df.cummin(axis=1))
      Product_A  Product_B
1月        100         50
2月        300        100
3月        200        200
4月        250        200
5月        300        250

五、cumprod 函数

统计从第一行(列)到当前行(列)的累乘值

# 1.沿行轴统计累乘值
print(df.cumprod())
       Product_A    Product_B
1月           100           50
2月         30000         5000
3月       6000000      1750000
4月    1500000000    350000000
5月  450000000000  87500000000
# 2.沿列轴统计累乘值
print(df.cumprod(axis=1))
     Product_A  Product_B
1月        100       5000
2月        300      30000
3月        200      70000
4月        250      50000
5月        300      75000

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com