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

使用Python基于通胀率更新销售额DataFrame:实现两DataFrame数值相乘

解决方案:销售额与通胀率匹配计算

问题说明

现有两个DataFrame:

  1. 销售额(Sales)表:
Code202520262027
123200002100022000
456100001200014000
  1. 通胀率(Inflation)表:
Code202020212022202320242025202620272028
1230.60.70.80.911.11.21.31.4
4560.550.650.750.8511.21.31.41.5

需要将销售额表中每个Code对应年份的数值,乘以通胀率表中同Code同年份的通胀率,得到更新后的销售额表。


实现代码(基于Pandas)

import pandas as pd

# 1. 构造原始DataFrame
# 销售额表
sales_data = {
    'Code': [123, 456],
    '2025': [20000, 10000],
    '2026': [21000, 12000],
    '2027': [22000, 14000]
}
sales_df = pd.DataFrame(sales_data)

# 通胀率表
inflation_data = {
    'Code': [123, 456],
    '2020': [0.6, 0.55],
    '2021': [0.7, 0.65],
    '2022': [0.8, 0.75],
    '2023': [0.9, 0.85],
    '2024': [1, 1],
    '2025': [1.1, 1.2],
    '2026': [1.2, 1.3],
    '2027': [1.3, 1.4],
    '2028': [1.4, 1.5]
}
inflation_df = pd.DataFrame(inflation_data)

# 2. 按Code匹配并计算更新后的销售额
# 将Code设为索引,确保行对齐
sales_indexed = sales_df.set_index('Code')
inflation_indexed = inflation_df.set_index('Code')

# 只选取销售额表中存在的年份列进行乘法运算
updated_sales = sales_indexed * inflation_indexed[sales_indexed.columns]

# 重置索引恢复Code列,并转换数值为整数
updated_sales = updated_sales.reset_index().astype({'2025': int, '2026': int, '2027': int})

# 输出结果
print(updated_sales)

运行结果

Code  2025  2026  2027
0   123  22000  25200  28600
1   456  12000  15600  19600

关键逻辑说明

  • 将Code设为索引,保证两个表的行按Code精准匹配
  • 通过sales_indexed.columns筛选通胀率表的对应年份列,避免无关列干扰
  • Pandas的DataFrame乘法会自动按索引和列名对齐,完成对应位置的数值相乘
  • 最后重置索引恢复原表结构,转换整数是为了贴合预期结果的格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:19:52