Python如何为各年份列赋值并计算GDP年度绝对及实际增长率?
1. 数据清洗
你拿到的原始GDP数据是带特殊符号的字符串,需要先处理成可计算的数值类型,核心是去掉$、逗号、M和多余空格,再转成浮点型:
# 原始GDP字符串列表 gdp_raw = ['$59,928M','$59,907M','$52,618 M','$61,018M','$85,658M'] # 清洗转换为数值(单位:十亿美元,和你后续y数组单位统一) gdp_numeric = [] for s in gdp_raw: # 过滤所有非数字/小数点的字符 clean_s = ''.join([c for c in s if c.isdigit() or c == '.']) # 转成数值后除以1000,和你现有y数组的单位(十亿美元)对齐 gdp_val = float(clean_s) / 1000 gdp_numeric.append(gdp_val) # 得到的gdp_numeric和你之前写的y数组完全一致:[59.928, 59.907, 52.618, 61.018, 85.658]
2. 计算年度增量与增长率
按你给出的公式遍历计算即可,2016年没有前序数据,增量和增长率默认填-:
years = [2016,2017,2018,2019,2020] abs_growth = [] # 绝对增量,单位:十亿美元 growth_rate = [] # 增长率,单位:% for i in range(len(gdp_numeric)): if i == 0: abs_growth.append('-') growth_rate.append('-') else: delta = gdp_numeric[i] - gdp_numeric[i-1] abs_growth.append(round(delta, 3)) rate = delta / gdp_numeric[i-1] * 100 growth_rate.append(round(rate, 2))
3. 计算结果表
| 年度 | GDP(十亿美元) | 年度绝对增量(十亿美元) | 年度增长率(%) |
|---|---|---|---|
| 2016 | 59.928 | - | - |
| 2017 | 59.907 | -0.021 | -0.04 |
| 2018 | 52.618 | -7.289 | -12.17 |
| 2019 | 61.018 | 8.4 | 15.96 |
| 2020 | 85.658 | 24.64 | 40.38 |
4. 优化后的完整可视化代码
在你原有代码基础上增加了柱子数值标注,可读性更强:
import numpy as np import matplotlib.pyplot as plt years = [2016,2017,2018,2019,2020] gdp = [59.928,59.907,52.618,61.018,85.658] fig, ax = plt.subplots() # 绘制GDP柱状图 bars = ax.bar(years, gdp, color='#2e8b57', alpha=0.7) # 给每个柱子标注对应GDP数值 for bar in bars: height = bar.get_height() ax.text(bar.get_x() + bar.get_width()/2., height, f'{height}B$', ha='center', va='bottom') ax.set_facecolor('seashell') fig.set_facecolor('floralwhite') fig.set_figwidth(12) fig.set_figheight(6) ax.set_title('2016-2020年GDP变化情况', fontsize=14) ax.set_ylabel('GDP(十亿美元)', fontsize=12) ax.set_xlabel('年度', fontsize=12) plt.xticks(years) plt.show()
内容的提问来源于stack exchange,提问作者Ductor Master
相关产品推荐
相关产品推荐

