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

Pandas选择指定固定列及近10年列数据有什么快捷写法?

针对这个需求,有两种更灵活的实现方式,不用手动逐个敲年份列:

方案1:固定指定年份范围

适合明确需要取固定时间段数据的场景,修改年份区间直接调整range参数即可:

# 定义固定字段列表
fixed_cols = ['Country Name', 'Country Code', 'Indicator Name', 'Indicator Code']
# 生成2010-2020的年份字符串列表,range的右边界要多写1位
year_cols = [str(y) for y in range(2010, 2021)]
# 合并列表后取数
GDP_filter = GDP[fixed_cols + year_cols]

方案2:自动取最新10年数据

适合数据集会持续更新,每次跑代码要自动拿最近10年数据的场景,不用手动修改年份参数:

fixed_cols = ['Country Name', 'Country Code', 'Indicator Name', 'Indicator Code']
# 筛选所有数值型列名(即年份列),倒序排序后取前10个最新年份
year_cols = sorted([col for col in GDP.columns if col.isdigit()], reverse=True)[:10]
# 把年份按从小到大排序
year_cols.sort()
GDP_filter = GDP[fixed_cols + year_cols]

补充说明

  • 两种写法都比手动列所有字段的方式易维护,调整字段或者时间范围只需要改对应参数即可
  • 第二种方案会自动适配数据集里的年份列,哪怕后续数据集更新到2021、2022年,也会自动取最新的10个年份的数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:54:04