You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用numpy.npv对pandas数据按项目分组计算各组的NPV值

实现方案

NPV计算需要匹配数据时间周期的折现率,以下示例以*月折现率1%*为例,你可以根据实际业务需求调整折现率数值。

完整实现代码如下:

import numpy as np
import pandas as pd

# 初始数据构建
data = [{'Month': '2020-01-01', 'Expense':1000, 'Revenue':5000, 'Building':'Stadium'}, 
       {'Month': '2020-02-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'},
       {'Month': '2020-03-01', 'Expense':7000, 'Revenue':5000, 'Building':'Stadium'}, 
       {'Month': '2020-04-01', 'Expense':3000, 'Revenue':4000, 'Building':'Stadium'},
       {'Month': '2020-01-01', 'Expense':5000, 'Revenue':6000, 'Building':'Casino'}, 
       {'Month': '2020-02-01', 'Expense':5000, 'Revenue':4000, 'Building':'Casino'},
       {'Month': '2020-03-01', 'Expense':5000, 'Revenue':9000, 'Building':'Casino'},
       {'Month': '2020-04-01', 'Expense':6000, 'Revenue':10000, 'Building':'Casino'}]
df = pd.DataFrame(data)

# 定义月折现率
discount_rate = 0.01

# 按Building分组计算Revenue的NPV,输出为DataFrame格式
npv_result = df.groupby('Building')['Revenue'].apply(
    lambda cash_flow: np.npv(rate=discount_rate, values=cash_flow)
).reset_index(name='Revenue_NPV')

print(npv_result)

如果你需要计算扣除支出后的净现金流NPV,可以调整分组逻辑:

npv_result_net = df.groupby('Building').apply(
    lambda group: np.npv(rate=discount_rate, values=group['Revenue'] - group['Expense'])
).reset_index(name='Net_Cashflow_NPV')

运行上述代码后得到的结果就是每个场所对应的NPV值,直接输出DataFrame格式,也可以按需转为列表使用。

内容的提问来源于stack exchange,提问作者ASH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:57:02