详解 Pandas 的累计统计函数

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

一、数据准备

import pandas as pd

df = 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值