使用Python基于通胀率更新销售额DataFrame:实现两DataFrame数值相乘
解决方案:销售额与通胀率匹配计算
问题说明
现有两个DataFrame:
- 销售额(Sales)表:
| Code | 2025 | 2026 | 2027 |
|---|---|---|---|
| 123 | 20000 | 21000 | 22000 |
| 456 | 10000 | 12000 | 14000 |
- 通胀率(Inflation)表:
| Code | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | 2026 | 2027 | 2028 |
|---|---|---|---|---|---|---|---|---|---|
| 123 | 0.6 | 0.7 | 0.8 | 0.9 | 1 | 1.1 | 1.2 | 1.3 | 1.4 |
| 456 | 0.55 | 0.65 | 0.75 | 0.85 | 1 | 1.2 | 1.3 | 1.4 | 1.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
相关产品推荐
相关产品推荐

