如何将Pandas中Vintage列转换为距今年份并更名
实现方法:将Vintage列转换为Age列(距今年份)
操作步骤
先确保已导入pandas和datetime模块,再按以下方式实现:
获取年份基准
可以用date.today().year动态获取系统当前年份,也可以直接指定固定年份(比如示例中2020对应Age=2,说明基准年份是2022,可按需调整)。计算Age列并调整列名
有两种简洁的实现方式:
方式一:新增Age列后删除原Vintage列
import pandas as pd from datetime import date # 假设你的DataFrame名为df current_year = date.today().year # 计算Age:基准年份减去Vintage的年份值 df['Age'] = current_year - df['Vintage'] # 删除原Vintage列 df.drop('Vintage', axis=1, inplace=True) # 可选:调整列顺序,将Age放在第一列 df = df[['Age', 'CprTarget']]
方式二:直接重命名列并修改值
import pandas as pd from datetime import date current_year = date.today().year # 先把Vintage列重命名为Age df.rename(columns={'Vintage': 'Age'}, inplace=True) # 计算Age值 df['Age'] = current_year - df['Age']
注意事项
- 若不需要动态获取当前年份,直接把
current_year替换为固定数值即可,比如current_year = 2022(匹配示例中的转换结果)。 - 因为Vintage列已是
int64类型,直接做减法运算不会有类型兼容问题。
内容的提问来源于stack exchange,提问作者Hefe
相关产品推荐
相关产品推荐

